Adrian Jałoszewski
Adrian Jałoszewski

Reputation: 1723

std::cin resulting in infinite loop

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.

Upvotes: 0

Views: 124

Answers (1)

Darklighter
Darklighter

Reputation: 2192

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.

Upvotes: 1

Related Questions