2017-10-09 12 views
-5
void Display::getInput(){ 
    cout << endl << endl << "Enter Command: "; 
    char input[MAX_LENGTH]; 
    cin >> input; 

    if (input == "start"){ 
    startMenu(); 
    } 

我得到这个错误,但我不知道为什么,因为我总是能使用此语法比较..当其中一个来自cin时,无法比较两个字符串。这里有什么问题?

Display.cpp:在成员函数“void显示:: getInput() “:

Display.cpp:20:16:警告:在 未指定的行为与字符串文字结果的比较[-Waddress]如果(输入== “开始”){

+0

使用'strcmp'代替? – Raindrop7

+2

如果使用'std :: string',这些问题会完全消失 – user463035818

回答

4

为了比较C风格字符串,你需要使用strcmp。否则,将input更改为字符串(std::string)而不是字符数组。你正在比较两个指针,其中一个指向一个文字,另一个指向一个数组,因此它们永远不会相等。

2

您不能比较类似的C风格字符串,而是使用strcmp来比较哪些成功时返回0,并且失败时返回非零。

或者你可以使用类string

int main(){ 
    char szInput[100]; 
    std::cin.getline(szInput, 100); 

    const char* szTest = "Hello"; 

    if(!strcmp(szInput, szTest)) 
     std::cout << "Identical" << std::endl; 
    else 
     std::cout << "Not identical" << std::endl; 


    std::string sInput; 
    std::getline(std::cin, sInput); // getline for white-spaces 

    std::string sTest = "Welcome there!"; 

    if(sTest == sInput) 
     std::cout << "Identical" << std::endl; 
    else 
     std::cout << "Not identical" << std::endl; 

    return 0; 
} 
  • 我以前getline代替cin采取计空格字符。
相关问题