Cin not waiting for input despite cin.ignore()

1.6k views Asked by At

I'm new to C++ and I'm using Visual Studio 2015.

cin is not waiting for input after "Please enter another integer:\n" and outputs "You entered 0" every time.

I've searched the Internet more than an hour without a solution. No combination of cin.ignore() is working. Why is the cin buffer still not cleared?

#include <iostream>
#include <vector>
using namespace std;

int main() {
        vector<int> vals;
        int val = 0;
        int n = 0;

        cout << "Please enter some integers (press a non-numerical key to stop)\n";
        while (cin >> val)
            vals.push_back(val);        

        cin.ignore(INT_MAX, '\n');
        cin.ignore();

        cout << "Please enter another integer:\n";

        cin.ignore();

        cin >> n;
        cout << "You entered " << n;

        system("pause");
        return 0;
}
3

There are 3 answers

2
Captain Giraffe On BEST ANSWER

The problem is for the user to exit the loop you need to put the cin in a failed state. That is why your

while(cin >> val){ .... }

is working.

If in a failed state cin is no longer in a position to supply you with input so you need to clear() the failed state. You also need to ignore() the previously non-integer response that triggered the failed state initially.

It would also be of merit to use

if(cin >> n){
    cout << "You entered " << n;
}

This will assert that a proper input for n was provided.

0
user On

The problem in your program is that it expects integers, whereas a user can input anything, like a non-integer char.

A better way to do what you seem to want to do is to read characters one by one, ignoring whitespace, and if it's a digit, then continue reading to get the whole number, else stop the loop. Then you can read all chars until you reach '\n', and do the same for one number. While you do that, for each character you should check that there can still be characters in the stream with cin.eof().

Also, instead of using system("pause"), you can prevent the command line window from closing by requesting a last character before terminating the application.

2
YouneS On

Try getting your integers like this :

#include <sstream>

...
fflush(stdin);
int myNum;
string userInput = "";

getline(cin, userInput);
stringstream s (userInput);
if (s >> myNum) // try to convert the input to int (if there is any int)
    vals.push_back(myNum);

without sstream you have to use try catch, so your programme won't crash when input is not an integer