本质上,我是 C++ 新手,正在制作一个非常基本的基于文本的 RPG 来娱乐。我的识别功能正常工作,但我必须非常精确地输入内容,否则我会被软锁定并且无法输入另一个字符串。 示例:
int main() {
cout << "You find yourself at the ending of a long hallway. The doorway opened to lead into a grand open cavern filled with ornate looking materials and a pedestal standing at the front. Walking over to the pedestal, you \n Take the book, \n read the book, \n burn the book?\n";
string input;
getline(cin, input);
if(input == "Burn the book"){
cout << "(what would happen)";
每当我输入“Burn the book”时,它都会正常工作,但是如果我不小心输入了错误的内容,我就不能再输入它,而且我必须重新启动编译器才能从头开始重试。有小费吗?我尝试使用“else”语句再次尝试使用 Getline 代码,但这似乎不起作用。
如果我没有输入正确的内容,我尝试使用“else”语句来尝试使其成为 getline,但它似乎没有按我的预期工作,我打算尝试“if else”声明,但我也没有让它发挥作用。当您输入错误时,也许有某种方法可以完全重新启动 getline 代码的该部分,但我不知道。
您可以使用
while
循环来实现您想要的:
std::string input;
while (input != "Burn the book");
{
std::getline(std::cin, input);
if (input != "Burn the book")
{
std::cout << "Invalid input\n"; //or whatever other error message you want
}
}
std::cout << "(what would happen)\n";
//...