使用while循环让用户给出布尔值输入



我刚刚开始学习C++并尝试学习语法。

#include <iostream>
#include <limits>
using namespace std;
int main(){
bool answer;
cout << "Did you enjoy testing this program? (1 for yes, 0 for no) ";
cin >> answer;
while (!(cin >> answer)) {
cout << "Invalid value!n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cout << "Please type either 0 or 1: ";
cin >> answer;
}
cout << "Your feedback has been registered. Feedback: " << answer;
}

目的是让用户反复询问,直到他们输入0或1。当给定其中任何一个值时,代码片段只会使事情冻结。该如何解决?

循环上方的cin >> answer;语句和循环体末尾的cin >> answer;语句都需要删除。

您提示用户输入一个值,然后读入该值并忽略它,然后等待用户输入另一个值(即使您没有提示用户输入超过1个值(。

如果他们确实输入了第二个值,但失败了,您的循环将提示用户输入一个新值,然后您读入该值并忽略它,然后您等待用户输入另一个值而不提示用户这样做

每次循环迭代只应调用cin >> answer一次,例如:

#include <iostream>
#include <limits>
using namespace std;
int main(){
bool answer;
cout << "Did you enjoy testing this program? (1 for yes, 0 for no) ";
// cin >> answer; // <- remove this!
while (!(cin >> answer)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cout << "Invalid value!n";
cout << "Please type either 0 or 1: ";
// cin >> answer; // <- remove this!
}
cout << "Your feedback has been registered. Feedback: " << answer;
}

最新更新