'error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'const char*' line 23
I am Comparing two strings but unfortunately this error occured
error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'const char*' line 23
#include<iostream>
#include<string.h>
using namespace std;
class car{
public:
int feulcp,batterycp,length,height,widht,seater,torque,power,temp;
char ownername[20],noplate[12],statecheck[20];
string statename[28]={"andhra pradesh","arunachal pradesh","assam,bihar","chhattisgarh","goa","gujarat","haryana","himachal pradesh","jharkhand","karnataka","kerala","madhya pradesh","maharashtra","manipur","meghalaya","mizoram","nagaland","odisha","punjab","rajasthan","sikkim","tamil nadu","telangana","tripura","uttarakhand","uttar pradesh","west bengal"};
car(){
cout<<"Please Enter Your State Name :";
y:
cin>>statecheck;
for(int i=0;i<=27;i++){
temp=strcmp(statename[i],statecheck);//here is the Error!!!
if(temp==0){
goto x;
}
else
cout<<"INVALID STATE NAME \n PLEASE RE-ENTER ";
goto y;
}
x:
cout<<"successfull";
}
};
int main(){
car car1;
return 0;
}
Solution 1:[1]
strcmp() takes const char* parameters, but you are passing it a std::string object instead, hence the error. Use the std::string::c_str() method to get a const char*:
temp = strcmp(statename[i].c_str(), statecheck);
That being said, there is no need to use strcmp() at all, as std::string has its own operator== and compare() methods for performing string comparisons, eg:
if (statename[i] == statecheck){
if (statename[i].compare(statecheck) == 0){
Solution 2:[2]
SYNOPSIS: strcmp()
`int strcmp(const char *s1, const char *s2);`
Both arguments for strcmp() should be interpreted as type unsigned char, and their difference is calculated.
`temp=strcmp(statename[i],statecheck);`
In your code "statename" is "std::string" and compiler fails the implicit conversion from std::string to const char*.
SOLUTION:
temp = strcmp(statename[i].c_str(), statecheck);
std::string::c_str : will represent current value of the string in C-string.
NOTE
Replacing :
char statecheck[20]; with std::string statecheck;
temp=strcmp(statename[i].c_str(),statecheck); and if(temp==0) with if(statename[i] == statecheck)
will be better and as Adrian Mole explained the code will fail to provide the expected result.
Pls free to correct incase of any mistakes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Vipin Chandran |
