Reputation: 21
I was comparing two strings, but unfortunately this error occurred
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, width, 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 << "successful";
}
};
int main() {
car car1;
return 0;
}
Upvotes: 1
Views: 25197
Reputation: 1
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 the compiler fails the implicit conversion from std::string to const char*.
temp = strcmp(statename[i].c_str(), statecheck);
std::string::c_str: will represent the current value of the string in C-string.
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.
Upvotes: 0
Reputation: 598309
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){
Upvotes: 1