6

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

5
  • is there an unprintable character like CR coming along with the input when you type or does cin grab one character? Commented Nov 27, 2013 at 22:39
  • Just use scanf. Way easier and clearer. Commented Nov 27, 2013 at 22:47
  • @Joker_vD But I thought this was C++... Commented Nov 27, 2013 at 22:48
  • scanf is never the right answer. To anything. Commented Nov 27, 2013 at 23:36
  • @qwrrty Well, scanf is marginally faster than cin >> (not sure why, it has to parse the format string), so if the question is "performance!1!!11elevenone", it may be the answer. Commented Nov 28, 2013 at 6:26

2 Answers 2

6

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');
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I couldn't even tell! :)
The point is that because the stream is in an error state ignore will also fail unless you clear the error first.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.