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: r1 - 2017-01-17 - JimSkon
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2019 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback