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.
whilewith 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.