[英]cin.fail while loop input Re-Entry
Just trying to check that the input is a boolean variable (1 or 0) for this problem. 仅尝试检查输入是否是此问题的布尔变量(1或0)。
However, whenever the while loop is triggered, (ie by not entering a 1 or 0), it just falls through and says that the condition is true. 但是,无论何时触发while循环(即,不输入1或0),它都会掉下来并说条件成立。
I would like for the user to be able to re-enter their input after an incorrect input. 我希望用户能够在输入错误之后重新输入他们的输入。 How would I go about doing this? 我将如何去做呢?
My code: 我的代码:
int main() {
bool a,b,c;
cout << "This program will determine the value of the condition !(a||b) && c " << endl;
cout << "Please enter boolean values for a, b, and c. (0=F, 1=T) ";
cin >> a;
while (cin.fail())
{
cin.ignore(1000,'|n');
cin.clear();
cout << "Error: Enter only 0 or 1" << endl;
cout << "Enter in a new value for a" << endl;
}
cin >> b;
cin >> c;
cout << "The condition !(xx||xx)&&xx ";
if(!(a||b) && c)
{
cout << "is true";
}
else
{
cout << "is false";
}
return 0;
}
You need to put cin >> a;
您需要输入cin >> a;
in at the end of your while loop. 在while循环的末尾。
cin.clear()
will remove the error and then the while loop will stop. cin.clear()
将消除错误,然后while循环将停止。
Like so: 像这样:
cin >> a;
while (cin.fail())
{
cin.clear();
cin.ignore(1000,'\n');
cout << "Error: Enter only 0 or 1" << endl;
cout << "Enter in a new value for a" << endl;
cin >> a;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.