我正在尝试使用 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” 时,它工作得很好,但是当我输入 “the dagger” 时,它说运行 else
代码,然后循环回到“你拿什么”,然后立即选择“ Dagger ”。
最佳答案
您正在将 std::cin
与 >>
运算符一起使用。此运算符读取格式化输入(字)而不是未格式化输入(行)。您的程序不是读取 “the dagger”
,而是简单地读取 “the”
,然后将 “dagger”
留在输入缓冲区中以备后用。
要将未格式化的输入读取到 choice
,请改用 std::getline(std::cin, choice);
。
关于C++ - 如果循环内的语句无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51689808/