Input Validation

​Using Stream State to Validate Input

cout << "Enter an integer: ";
int val;
cin >> val;
cout << "You entered: " << val << endl;
output
cout << "Enter an integer: ";
int val;
cin >> val;
while(!cin.good()) { // any of the stream state bits is set
    cin.clear(); // set all stream state bits to zero, buffer NOT cleared
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    // clear the buffer of everything, i.e. make clean slate for input
    
    cout << "Enter a valid integer: ";
    cin >> val;
}
cout << "You entered: " << val << endl;

Checking for errors in our input

cin.clear();
  • Clear stream states

  • Does NOT affect buffer (so whatever caused problem is still in the buffer)

cin.ignore(numeric_limits<streamsize>::max(), '\n');
  • First parameter – max number of characters to ignore (i.e. remove from buffer)

  • Second parameter – character to stop ignoring characters if found before max number of characters removed from buffer

  • If ignore() is called with no arguments, cin will only skip the very next character

  • numeric_limits – different streams have different sizes, using this ensures that if the buffer is completely full, it will remove all of it.

  • '\n' – character representing end of line.

  • #include to use numeric_limits

• bad()
Returns true if a reading or writing operation fails.
For example, in the case that we try to write to a file that is not
open for writing or if the device where we try to write has no space left.

• fail()
Returns true in the same cases as bad(), but also in the case that a format error
happens, like when an alphabetical character is extracted when we are trying
to read an integer number.

• eof()
Returns true if a file open for reading has reached the end.

• good()
It is the most generic state flag: it returns false in the same cases in which calling
any of the previous functions would return true. Note that good and bad are not
exact opposites (good checks more state flags at once).

The member function clear() can be used to reset the state flags.

Last updated

Was this helpful?