我的c ++程序似乎无法证明字符串与我使用getline输入但要输入的变量之间的比较

问题描述 投票:0回答:1

我有一个名为input的字符串变量,我使用getline将文本输入到其中。当我尝试将变量input与另一个字符串(例如if(input == "new game"))进行比较时,它似乎没有评估比较。我知道它实际上是在输入正确的文本,因为当我在cout上使用input时,它会正确输出(在“新游戏”中键入将输出“新游戏”)。我查找了getline的问题,并看到cin留在了\n所选择的输入字符串中的getline后面。我尝试使用cin.ignore()cin.clear()cin.sync(),但它们似乎无法解决问题。此外,在getline(cin, input)之前没有任何输入。有问题的代码是打击,感谢您的任何帮助,谢谢!

int main(){
string input;
while(input != "quit"){
    getline(cin, input);
    if(input == "new game"){
        town(player);
    }
    if(input == "load game"){
        cout << "enter save file: " << endl;
        load(player);
    }
}
return 0;

}

c++ string comparison cin getline
1个回答
0
投票

我发现错误,您一开始就忘记了include string模块。仅包含字符串,它将正常工作。

  #include <iostream>
  #include <string>
  using namespace std;
      int main(){
        string input;
          while(input != "quit"){
            getline(cin, input);
           if(input == "new game"){
             town(player);
         }
           if(input == "load game"){
             cout << "enter save file: " << endl;
             load(player);
         }
      } 
    return 0;
  }
© www.soinside.com 2019 - 2024. All rights reserved.