I have a question which is slightly similar to this question on stackoverflow std::cin.clear() fails to restore input stream in a good state, but the answer provided there does not work for me.
The question is: how can I reset the state of a stream to 'good' again?
Here is my code how I try it, but the state is never set to good again. I used both of the lines ignore separately.
int _tmain(int argc, _TCHAR* argv[])
{
int result;
while ( std::cin.good() )
{
std::cout << "Choose a number: ";
std::cin >> result;
// Check if input is valid
if (std::cin.bad())
{
throw std::runtime_error("IO stream corrupted");
}
else if (std::cin.fail())
{
std::cerr << "Invalid input: input must be a number." << std::endl;
std::cin.clear(std::istream::failbit);
std::cin.ignore();
std::cin.ignore(INT_MAX,'
');
continue;
}
else
{
std::cout << "You input the number: " << result << std::endl;
}
}
return 0;
}
See Question&Answers more detail:os