我正在比较两个字符串,但不幸的是发生了这个错误
错误:无法将'std::__cxx11::string' {aka 'std::_cxx11::basic_string'}转换为'const char*'行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;
}
字符串
2条答案
按热度按时间aiazj4mn1#
strcmp()
接受const char*
参数,但你传递给它的是一个std::string
对象,因此出现了错误。使用std::string::c_str()
方法获取一个const char*
:字符串
也就是说,根本不需要使用
strcmp()
,因为std::string
有自己的operator==
和compare()
方法来执行字符串比较,例如:的数据
yxyvkwin2#
简介:strcmp()
字符串
strcmp()的两个参数都应该解释为unsigned char类型,并计算它们的差异。
型
在您的代码中,“statename”是“std::string”,编译器将std::string隐式转换为const char* 失败。
解决方案
型
注意事项
更换:
char statecheck[20];
与std::string statecheck;
temp=strcmp(statename[i].c_str(),statecheck);
和if(temp==0)
与if(statename[i] == statecheck)
会更好,正如Adrian Mole解释的那样,代码将无法提供预期的结果。