0

I have a code in which I have to read integers up till user gives a string "q" then display and do stuff with them. I have to repeat that again and again up till user wants. We can clear the error flag by using cin.clear(). The problem is after the failed attempt to read int (user gave q) it does not read input and gives some arbitrary input to next ones. Here's the code boiled down to necessary things:

#include <iostream>
using namespace std;

int main(){

    // Declare the variables
    int x,y;

    // Read the wrong input - setting error flag
    cin >> x; // Give a string as input for eg. - "q" 
              // Without the quotes obviously 

    // Clear the error flag
    cin.clear();

    // Try to read again and display
    cin >> y; // Error!! Does not read input and
    cout << y << endl; // Displays 0

    return 0;
}

If I add more variables it gives some random stuff like 4309712, -1241221 etc. What is happening here? Why isn't cin.clear() working?

Compiler Properties

-------------- Build: Debug in Competition (compiler: GNU GCC Compiler)---------------

mingw32-g++.exe -Wall -fexceptions -g -std=c++14  -c D:\CP\Competition\main.cpp -o obj\Debug\main.o
mingw32-g++.exe  -o bin\Debug\Competition.exe obj\Debug\main.o   
Output file is bin\Debug\Competition.exe with size 1.05 MB
Process terminated with status 0 (0 minute(s), 0 second(s))
0 error(s), 0 warning(s) (0 minute(s), 0 second(s))

IDE Codeblocks 16.01

Existent
  • 697
  • 1
  • 7
  • 14

1 Answers1

0

Call of clear doesn't remove wrong input from stream. You should use ignore after clear to remove unnecessary characters. E.g.:

 cin.clear();
 cin.ignore(std::numeric_limits<streamsize>::max(),' ');

Also refer to references

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
VolAnd
  • 6,367
  • 3
  • 25
  • 43