Stephan Dollberg
Stephan Dollberg

Reputation: 34638

question concerning cin.clear()

I am just working through the book Accelerated C++. (My problem is located on page 57, if you guys have the book with you)

The problem is the following: We do have a function which reads student grades:

...
while (in >> x) {    // in and x are defined as an istream& and as a double
    hw.push_back(x);    // hw is vector defined as vector<double>&
}
in.clear();
...

Now, in book and also on the cplusplus.com refernce is stated that the clear function resets all the error states and that the input is now again ready to read some input. The problem is that if I put a:

int a = 0;
cin >> a;
cout << a << endl;

after the function it jumps the cin and just gives me a 0. Did I understand the function of cin.clear() totally wrong or what can I do to get the cin active again.

As I had the same problem a while before I read the book, I know that I solved the problem back then with the following line:

    cin.ignore( numeric_limits<streamsize>::max(), '\n');

Of course I then have to hit an extra enter key but it eats all the stuff which comes before and which makes the cin not to work.

The thing is that neither .clear nor .ignore work properly alone but using them both together I am able to enter something for the variable a;

EDIT: Ok, here is the whole code. This is something I have written myself, which is not from the book.

istream& in = cin; 
int var = 0;
vector<int> vec;
while ( in >> var ) { 
    vec.push_back(var); 
}
for (int f = 0; f < vec.size(); ++f) {
    cout << vec[f] << endl;
}
cin.clear();
cout << "cleared" << endl;
    int a = 0;
    cin >> a;
    cout << a << endl;

Upvotes: 0

Views: 495

Answers (2)

Ren&#233; Richter
Ren&#233; Richter

Reputation: 3909

The while loop in your code example reads integer values until the end of input or an error occurs while reading, e.g. giving a character that cannot occur as an integer digit like 'q'.

When an error occured, you might have a chance to recover from that error by calling clear() and then removing the offending character from cin's input buffer:

char dummy;
cin >> dymmy;

Then you can read an int again.

Upvotes: 2

Bo Persson
Bo Persson

Reputation: 92401

The call to clear clears the error state set by a failed read. It doesn't do anything with the characters that might be present in the input stream.

If the error state is a result of failing to read a double, it is likely that the next character will also fail as an integer.

If you try

char ch;
cin >> ch;

I'm sure that will work better.

Otherwise you will have to ignore some characters to get rid of the unreadable input.

Upvotes: 3

Related Questions