2

I am currently working on a c++ program and I want to check to see if the input the user is making is valid. Currently my code works if the user inputs the proper input or if the user inputs a small incorrect number my pogram will tell the user that the input is invalid. Now my problem is that when the user inputs multiple characters/letters or a large number that has 9 or more digits in it my program goes into an infinate loop giving them the error message. The following is my code:

//for (;;)
    while (flag== false)
    {
        cin >> Input;
        if (Input <= choice.size()-1)
        {
            flag = true;
    //  break;
        }

        else
        {
            cerr << "Input <" << Input << "> is Invalid, Please Choose a Valid Option\n";
            userInput = 0;
        }
    }

As you can see I have also tried doing an infinate for loop but it gives me the same results. In my code i am printing a vector to the screen. Basicly the user it picking the vectors value to use it.

I am open to any suggestions. Thanks

Johnston
  • 2,873
  • 8
  • 29
  • 39
  • possible duplicate of [how do I validate user input as a double in C++?](http://stackoverflow.com/questions/3273993/how-do-i-validate-user-input-as-a-double-in-c) – casablanca Nov 14 '10 at 18:28

1 Answers1

2

If the user types in something that can't be read into Input (it's not clear from your code what type Input is), that input will get stuck in the input stream and each iteration of the loop will keep failing to read in the input until you clear the stream.

You need to clear the stream flags and get rid of whatever bad input is waiting in the stream after each failure to read. Try something like this:

while(!(cin >> Input) || Input <= choice.size()-1)
{
  cerr << "Input <" << Input << "> is Invalid, Please Choose a Valid Option\n";
  cin.clear(); // Clears the input stream fail flag
  cin.ignore(100, '\n'); // Ignores any characters left in the stream
}
user168715
  • 5,469
  • 1
  • 31
  • 42
  • `cin.sync()` is a better option than specifying a hard-coded value such as 100. – casablanca Nov 14 '10 at 19:01
  • Does `sync` work portably? http://www.cplusplus.com/reference/iostream/istream/sync/ is less than clear about what calling `sync` on `cin` is guaranteed to do, and the comments at http://stackoverflow.com/questions/3273993/how-do-i-validate-user-input-as-a-double-in-c aren't too encouraging. – user168715 Nov 14 '10 at 20:45