Reputation: 3
Just trying to check that the input is a boolean variable (1 or 0) for this problem.
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;
}
Upvotes: 0
Views: 6822
Reputation: 2520
You need to put cin >> a;
in at the end of your while loop.
cin.clear()
will remove the error and then the while loop will stop.
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;
}
Upvotes: 1