23

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);
1
  • Very old, but very good question. Commented Aug 26, 2024 at 5:46

4 Answers 4

38

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, this is more along the lines of what I was looking for. Much appreciated. One question though, what is the for loop condition (;;)? Don't understand that.
@Alex - foo(;;) means loop forever, just like while(1). If you don't want your loop to truly loop forever, you need a break somewhere inside to terminate the loop.
I'd typically have while(!eof(stdin)) in such a case, to avoid the code go crazy if the input is lost... or will that throw an exception here ?
Old, but very good answer.
6
int taxableIncome;
string strInput = "";
cout << "Please enter in your taxable income:\n";

while (true) 
{
    getline(cin, strInput);

    // This code converts from string to number safely.
    stringstream myStream(strInput);
    if ( (myStream >> taxableIncome) )
        break;
    cout << "Invalid input, please try again" << endl;
}

So you see I use string for input and then convert that to an integer. This way, someone could type enter, 'mickey mouse' or whatever and it will still respond.
Also #include <string> and <sstream>

1 Comment

while (true) { getline(cin, strInput); ... } should be while (getline(cin, strInput)) { ... }
4

One minor quibble is that the error helper variable is completely redundant and is not needed:

do
{
    cin.clear();
    cout << "Please enter in your taxable income: ";
    cin >> taxableIncome;
    if (cin.fail())
    {
        cout << "Please enter a valid integer" << endl;
        cin.ignore(80, '\n');
    }
}while(cin.fail());

1 Comment

You should not be calling cin.clear() before reading from cin. You should call cin.clear() only if reading actually fails. IOW, move it inside your if block before calling cin.ignore(). As for ignore() itself, you should use std::numeric_limits<std::streamsize>::max() instead of hard-coding 80.
2

Might you not consider try/catch, just to get you used to the concept of exception handling?

If not, why not use a boolean, instead of 0 and 1? Get into the habit of using variables of the correct type (and of creating types where needed)

Cin.fail() is also discussed at http://www.cplusplus.com/forum/beginner/2957/

In fact, in many places ...

http://www.google.com.sg/#hl=en&source=hp&q=c%2B%2B+tutorial&btnG=Google+Search&meta=&aq=f&oq=c%2B%2B+tutorial

you might study some of those and try to follow the explanations of why things should be done a certain way.

But, sooner or later, you ought to understand exceptions...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.