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.

Community
  • 1
  • 1
Adrian Jałoszewski
  • 1,695
  • 3
  • 17
  • 33
  • 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? – Kerrek SB Mar 26 '17 at 00: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. – Adrian Jałoszewski Mar 26 '17 at 00:14
  • Well, you have ignore and clear mixed up, but this is still weird code. – Kerrek SB Mar 26 '17 at 00:18
  • Thanks, that changing the order worked for me. Maybe I should consult my rubber duck more often. – Adrian Jałoszewski Mar 26 '17 at 00:25

1 Answers1

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.

Darklighter
  • 2,082
  • 1
  • 16
  • 21