Checking For Valid Input
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
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
}
精彩评论