0

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?

iBug
  • 35,554
  • 7
  • 89
  • 134
  • 2
    @Sahu I don't think so - he wants to keep looping until he gets a valid integer. –  Oct 27 '17 at 15:29
  • I believe your data "a" in your example is stored in d. Once that happens the getline doesn't retrieve any useful data. Hence `waste` never change value. – Stefano Buora Oct 27 '17 at 15:29
  • 1
    @iBug Get rid of the string stuff, and swap the order of ignore and clear. I've got a blog article on this at https://latedev.wordpress.com/2011/09/13/simple-input-bullet-proofing-in-c/ –  Oct 27 '17 at 15:30
  • @NeilButterworth Can you explain why should I swap the order of `ignore` and `clear`? – iBug Oct 27 '17 at 15:31
  • @iBug Because if you don't clear the stream, it's still bad, so ignore will not work correctly. –  Oct 27 '17 at 15:32

0 Answers0