循环输入重新输入时cin.fail [英] cin.fail while loop input Re-Entry
本文介绍了循环输入重新输入时cin.fail的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
仅尝试检查输入是否为此问题的布尔变量(1或0).
Just trying to check that the input is a boolean variable (1 or 0) for this problem.
但是,无论何时触发while循环(即不输入1或0),它都会掉下来并说条件为真.
However, whenever the while loop is triggered, (i.e. by not entering a 1 or 0), it just falls through and says that the condition is true.
我希望用户能够在输入错误之后重新输入他们的输入.我将如何去做呢?
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;
}
推荐答案
您需要输入 cin>>a;
在while循环的末尾.
You need to put cin >> a;
in at the end of your while loop.
cin.clear()
将消除该错误,然后while循环将停止.
cin.clear()
will remove the error and then the while loop will stop.
像这样:
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;
}
这篇关于循环输入重新输入时cin.fail的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文