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.


The problem you are having is that you don't clear the failbit from the stream. This is done with the clear function.


On a somewhat related note, you don't really need to use the fail function at all, instead rely of the fact that the input operator function returns the stream, and that streams can be used in boolean conditions, then you could do something like the following (untested) code:

while (!(std::cin >> iUserSel))
{
    // Clear errors (like the failbit flag)
    std::cin.clear();

    // Throw away the rest of the line
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    std::cout << "Wrong input, please enter a number: ";
}

Here's what I would recommend:

// Read the data and check whether read was successful.
// If read was successful, break out of the loop.
// Otherwise, enter the loop.
while ( !(cin >> iUserSel) )
{
   // If we have reached EOF, break of the loop or exit.
   if ( cin.eof() )
   {
      // exit(0); ????
      break;
   }

   // Clear the error state of the stream.
   cin.clear();

   // Ignore rest of the line.
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

   // Ask more fresh input.
   cout << "Wrong! Enter a #!" << endl;
}