[英]C++ - If statement inside loop not working properly
我正在尝试使用std::cin
同时将一个选项循环回到开始。 循环工作正常,但是当我在if
语句之一中添加一个附加选项然后键入时,它不会认为我选择的是选项。
#include <iostream>
#include <string>
#include <windows.h>
#include <chrono>
#include <thread>
using namespace std;
int main() {
string choice;
char restart;
do {
choice.clear();
cout << "Which do you take? " << endl;
cin >> choice;
if (choice == "all") {
//cout code
restart = 'y';
}
else if (choice == "dagger" || choice == "the dagger") {
choice.clear();
cout << "You pick up the dagger" << endl << endl;
return 0;
}
else {
choice.clear();
cout << "That isn't an option, pick again... "<< endl << endl;
sleep_for(1s);
restart = 'y';
}
} while (restart == 'y');
}
当我输入“ dagger”时 ,它工作得很好,但是当我输入“ dagger”时,它说运行else
代码,然后循环回到“ Which you take” ,然后立即选择“ dagger” 。
您正在使用带有>>
运算符的std::cin
。 该操作员读取格式化的输入(单词)而不是未格式化的输入(行)。 程序不是读取"the dagger"
,而是读取"the"
,并将"dagger"
留在输入缓冲区中以备后用。
要读取choice
未格式化输入,请使用std::getline(std::cin, choice);
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.