0

I'm experiencing an infinite loop in a simple and tiny C++ code where I try to read user input and repeat when input fails until it correctly fills an integral type:

std::size_t size{};

while (std::cout << "Enter size: " && !(std::cin >> size))
{   
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << std::endl;
}

But despite clearing std::cin and ignoring buffer contents, the loop gets running infinitely without prompting for user input.

What am I missing?
What should be done to make std::cin block io and read user input in each iteration after it fails?

Brian Salehi
  • 414
  • 2
  • 10
  • 19
  • Works fine [here](https://godbolt.org/z/vc7x5ebWo). It fails for the first two inputs, accepts the input of 42 and then exits the loop. – NathanOliver Jan 19 '23 at 21:29
  • @NathanOliver I just realized that maybe by entering eof the input stream gets closed, so I replaced std::cin with std::fstream("/dev/tty") and it was a fix. I'm not sure if it really gets closed but the failure is not recoverable I guess. – Brian Salehi Jan 19 '23 at 21:34
  • 4
    EOF ends the stdin input stream so you can't recover from that. – NathanOliver Jan 19 '23 at 21:36
  • related/dupe: https://stackoverflow.com/questions/58732434/cin-clear-leave-eof-in-stream – NathanOliver Jan 19 '23 at 21:37
  • @NathanOliver Before I visit that link, I tried std::cin.putback('\n') after clearning buffer, and then ignoring everything in the buffer until '\n' is reached, and it actually worked! I'm still not sure what's happening to the stream though. Then I tried std::clearerr(stdin) mentioned in the link, and it also worked. Hope to see someone explaining what's happening under the hood. – Brian Salehi Jan 19 '23 at 21:48
  • 1
    After some thinking, now I realized that the change of stream actually means something and I should not ignore it. By resetting stream state, I'm only asking to keep reading from stream despite its state change which is totally a mistake in the design of a program. If user attempts to close the stream, program should cancel any ongoing operation and fallback into its previous operations. – Brian Salehi Jan 19 '23 at 21:53

0 Answers0