template boy
template boy

Reputation: 10480

Why does this code give me an infinite loop?

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:

enter image description here

Upvotes: 6

Views: 396

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 476940

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.

Upvotes: 4

john
john

Reputation: 87944

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');

Upvotes: 6

Related Questions