简体   繁体   中英

cin.fail while loop input Re-Entry

Just trying to check that the input is a boolean variable (1 or 0) for this problem.

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.

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; 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM