【问题标题】:error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'const char*' line 23错误:无法将 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} 转换为 'const char*' 第 23 行
【发布时间】:2021-10-28 02:35:39
【问题描述】:

我正在比较两个字符串,但不幸的是发生了这个错误

错误:无法将 '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,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;
}

【问题讨论】:

  • 您可以使用std::stringc_str() 成员函数来获得char* 可供strcmp 使用。但是您的代码中还有其他问题(可能是拼写错误) - 请尝试整理您的帖子。
  • 好的,我刚刚编辑了。
  • 好吧,除了在C++中很少有理由使用goto语句之外,问问自己如果输入的状态文本与列表中的第一个。您的代码将如何针对列表中的第二个进行测试?还是第三个?
  • 另外,在您#include &lt;string&gt; 之前,没有正式规定的std::string。如果你使用 std::string 类,you must include &lt;string&gt;。没有例外,如果它似乎起作用,那只是意味着你掷骰子并且你的汽车轮胎没有压扁。

标签: c++


【解决方案1】:

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){

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 2018-03-11
    • 1970-01-01
    相关资源
    最近更新 更多