2017-10-09 17 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採取計空格字符。