Dealing with character data input for an numeric (int or double) value.

If someone enters a string or character to the following:

int x;
cin << x;

The program no longer accepts input, cin is in an error state. You can recognize this case, and deal wit it:

int x;
cin >> x;
while ( cin.fail() ) // Check if there was an input error
{
     cin.clear(); // Clear the error
     cin.ignore(100,'\n'); // Remove everything in the input buffer (up to the last 100 characters)
     cout << "You must enter a number" << endl;
     cin >> x 
}
Topic revision: r2 - 2015-10-05 - JimSkon
 
This site is powered by the TWiki collaboration platformCopyright &© by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback