When cin
fails, it fails for ever. I.e. I can't read anything afterwards and cin.fail()
always returns true, no matter how I try to clear it.
Minimal code to recreate:
#include <iostream>
using namespace std;
int main(){
int d;
while (!(cin >> d)) // Loop until I get a valid integer
{
cin.ignore(9999, '\n');
cin.clear();
}
cout << d << endl;
return 0;
}
With minimal input:
a<Enter>
I tried all C++ answers under this question, but none of them worked. Strangely enough, fflush(stdin)
did a good job.
I use Dev-C++ as my IDE and replaced its packaged GCC with MinGW GCC 6.3.0 from SourceForge. The following arguments are supplied to g++.exe
when compiling
-Wall -Wextra -std=c++14 -s -O3 -static-libgcc -static-libstdc++
The same issue has also occurred with GCC 7.2.0 on my Ubuntu without the last two -static
arguments.
As suggested in comments, swapping the order of cin.clear()
and cin.ignore()
worked. What's the reason for that?