c++ 错误:无法将'std::__cxx11::string' {aka 'std::_cxx11::basic_string< char>'}转换为'const char*'行23

ymdaylpp  于 2023-11-19  发布在  其他
关注(0)|答案(2)|浏览(473)

我正在比较两个字符串,但不幸的是发生了这个错误
错误:无法将'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;
}

字符串

aiazj4mn

aiazj4mn1#

strcmp()接受const char*参数,但你传递给它的是一个std::string对象,因此出现了错误。使用std::string::c_str()方法获取一个const char*

temp = strcmp(statename[i].c_str(), statecheck);

字符串
也就是说,根本不需要使用strcmp(),因为std::string有自己的operator==compare()方法来执行字符串比较,例如:

if (statename[i] == statecheck){
if (statename[i].compare(statecheck) == 0){

的数据

yxyvkwin

yxyvkwin2#

简介:strcmp()

int strcmp(const char *s1, const char *s2);

字符串
strcmp()的两个参数都应该解释为unsigned char类型,并计算它们的差异。

temp=strcmp(statename[i],statecheck);


在您的代码中,“statename”是“std::string”,编译器将std::string隐式转换为const char* 失败。

解决方案

temp = strcmp(statename[i].c_str(), statecheck);

  • std::string::c_str*:将在C-string中表示字符串的当前值。

注意事项

更换:
char statecheck[20];std::string statecheck;temp=strcmp(statename[i].c_str(),statecheck);if(temp==0)if(statename[i] == statecheck)
会更好,正如Adrian Mole解释的那样,代码将无法提供预期的结果。

相关问题