I’m in my second OOP class, and my first class was taught in C#, so I’m new to C++ and currently I am practicing input validation using cin. So here’s my question:
Is this loop I constructed a pretty good way of validating input? Or is there a more common/accepted way of doing it?
Thanks!
Code:
int taxableIncome;
int error;
// input validation loop
do
{
error = 0;
cout << "Please enter in your taxable income: ";
cin >> taxableIncome;
if (cin.fail())
{
cout << "Please enter a valid integer" << endl;
error = 1;
cin.clear();
cin.ignore(80, '\n');
}
}while(error == 1);
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
boolif you keep it). You can put the read fromcindirectly into anif, which is perhaps more of a Perl idiom.Here’s my take:
Apart from only skipping 80 characters, these are only minor quibbles, and are more a matter of preferred style.