Why does this code give me an infinite loop?

When I enter the correct value (integer), thatโ€™s good. But when I enter the symbol, I get an infinite loop. I looked at all sides of this code and could not find a problem with it. Why is this happening? I am 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

+6
source share
2 answers

This is because your recovery operations are in the wrong order. Clear the error first, then clear the buffer.

  std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
+6
source

You must first clear indicate the status of the error, and then ignore uncontrolled buffer content. Otherwise, ignore do nothing on a thread that is not in good condition.

You will need to deal with reaching the end of the stream.

+4
source

Source: https://habr.com/ru/post/958965/


All Articles