How to use cin.fail() in c++ properly

When cin fails, you need to clear the error flag. Otherwise subsequent input operations will be a non op.

To clear the error flags, you need to call cin.clear().

Your code would then become:

cin >> iUserSel;
while (iValid == 1)
{
    if (cin.fail())
    {
        cin.clear(); // clears error flags
        cin.ignore();
        cout << "Wrong! Enter a #!" << endl;
        cin >> iUserSel;
    }//closes if
    else
        iValid = 0;
}//closes while

I would also suggest you change

cin.ignore(); 

to

cin.ignore(numeric_limits<streamsize>::max(), '\n'); 

In case the user enters more than one letter.

Leave a Comment