When I enter in a correct value (an integer) it is good. But when I enter in a character, I get an infinite loop. I've looked at every side of this code and could not find a problem with it. Why is this happening? I'm using g++ 4.7 on Windows.
#include <iostream>
#include <limits>
int main()
{
int n;
while (!(std::cin >> n))
{
std::cout << "Please try again.\n";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.clear();
}
}
Input: x
Output:
It's because your recover operations are in the wrong order. First clear the error then clear the buffer.
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
You have to clear
the error state first, and then ignore
the unparsable buffer content. Otherwise, ignore
will do nothing on a stream that's not in a good state.
You will separately need to deal with reaching the end of the stream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With