Good input validation loop using cin – C++

I’m not a huge fan of turning on exceptions for iostreams. I/O errors aren’t exceptional enough, in that errors are often very likely. I prefer only to use exceptions for less frequent error conditions.

The code isn’t bad, but skipping 80 characters is a bit arbitrary, and the error variable isn’t necessary if you fiddle with the loop (and should be bool if you keep it). You can put the read from cin directly into an if, which is perhaps more of a Perl idiom.

Here’s my take:

int taxableIncome;

for (;;) {
    cout << "Please enter in your taxable income: ";
    if (cin >> taxableIncome) {
        break;
    } else {
        cout << "Please enter a valid integer" << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
}

Apart from only skipping 80 characters, these are only minor quibbles, and are more a matter of preferred style.

Leave a Comment