0

Why does the following code result in an infinite loop when entering a character or a string? I've seen questions about it, and the solutions provided in the answers (example here), but it does not seem to help at all. The code implements the solutions suggested there, but it still results in an infinite loop.

#include <iostream>
#include <bitset>
#include <limits>
using namespace std;

int main() {
  int n;
  while (!(cin >> n)) {
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cin.clear();
    cout << std::bitset<8>(cin.rdstate()) << endl;
    cin >> n;
    cout << std::bitset<8>(cin.rdstate()) << endl;
  }
  cout << n;
  return 0;
}

g++ --version yelds the folowing: g++ (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005

The output of the program is as follows:

00000000
00000100
00000000
00000100
... and so on 

It seems like the value is beeing reentered despite the fact that the stream has been cleared and all input has been ignored.

4
  • That is a really strange variant on this I/O code, and I've seen a lot of messed-up stuff. What are you actually trying to do? Commented Mar 26, 2017 at 0:10
  • Originally I just tried to answer another question on SO, using the while with the clearing and ignoring - which should just work fine, the loop should terminate when a correct input is given (a number) and it should ask for a number until it gets one. But it never asks for another input - as if the previous one would be still provided. Basically the question contains not the starting point, but the debugging attempts. Commented Mar 26, 2017 at 0:14
  • Well, you have ignore and clear mixed up, but this is still weird code. Commented Mar 26, 2017 at 0:18
  • Thanks, that changing the order worked for me. Maybe I should consult my rubber duck more often. Commented Mar 26, 2017 at 0:25

1 Answer 1

1

You call ignore before clear, but ignore only works if the stream has no errors, but it always has at that point.
When you switch both statements it works fine: after one or several invalid inputs, you need 2 consecutive valid inputs to successfully terminate the program.

Sign up to request clarification or add additional context in comments.

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.