Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 800
template boy Avatar asked Nov 27 '13 22:11

template boy


2 Answers

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');
like image 118
john Avatar answered Sep 22 '22 15:09

john


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.

like image 30
Kerrek SB Avatar answered Sep 19 '22 15:09

Kerrek SB