PDA

View Full Version : (C++) while loop + cin.good = infinite loop?


Scriptdaemon
11-17-2007, 02:40 AM
Example:



cout << "Enter a year to display the first month of that year: ";
cin >> year;
while(year < 1 || !cin.good())
{
cout << endl << "Invalid year!" << endl
<< "Enter a year to display the first month of that year: ";
cin >> year;
}



It asks me to enter the year, and I do. If it's not a number, it just runs the loop over and over. I've used it in an if statement to check if a user enters letters instead of numbers before and it checked a value and returned an error as I expected, but in a while loop, it doesn't work as I expected, and runs the loop over and over without prompting me to re-enter the year, how can I fix this?

rpgfan3233
11-17-2007, 03:36 AM
if (!cin.good()) {
cin.clear(); //clear the error flags
cin.sync(); //flush the input buffer
}I forget if that is the order or if it needs to be the other way, or if it is fine either way, but it should work for you. You should be able to figure out where to place it. :thumbsup:

Scriptdaemon
11-17-2007, 03:42 AM
Thank you, that worked. I had a feeling I had to clear something for it to work.