我有一个名为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;
}
我发现错误,您一开始就忘记了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;
}