Writing a program for school and the error checking of one my functions will send the program into an infinite loop and I can't figure out why or how to fix it. As you can see below, it receives keyboard input to the int "testInput" variable. If I enter a number other than 0, 1, or 2, the default statement outputs an error and it correctly loops back for new input. However, if I submit any non-digit character, it goes into an infinite loop. I'm writing this is Codeblocks 12.11 with Mingw for compiler on a Windows XP machine.
Thanks for looking!
// Enumerated type declaration
enum listStatus {AVAILABLE, CONTRACT, SOLD};
#include <iostream>
int main( int argc, char* argv[] )
{
int input;
std::cout << "Please enter a choice between 0 and 2: ";
while( !( std::cin >> input ) || input < 0 || input > 2 )
{
std::cout << "Invalid input, please enter again: ";
std::cin.clear();
std::cin.ignore( 256, '\n' );
}
std::cout << "Valid input.\n";
return 0;
}
It might look a little crazy, but essentially the first condition in that loop is checking to see if the value that has been input is suitable for the type of the variable. It's a little more abstract than that, but that's the simplest way of looking at it, in my opinion.
Everything else there should look familiar, with the exception of clear and ignore. If you enter this loop, cin will be in a failed state. Clear will remove any error flags. Ignore gets rid of the data in it (in this case, I've picked a reasonably arbitrary amount of 256 or to the next newline. You can use limits to set correct amounts for this if you wish).
Sorry it took me a while to get back to your response - that assignment was kicking my butt and was already two days overdue... After looking over your example, I determined that I could use my original code and all I needed was to add 'cin.ignore' below my 'cin.clear' statement. I'm still a bit shaky on what these actually do or at least the difference between the two and why you would need to use one or the other or both.