using IO library condition state

Hi, guys. I was just now reading about IO library condition state and it says in my textbook that you can actually reset all condition of an IO type object to valid state, so I tried it out with the code written below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
int main()
{
    int a = 0;
    while(cin >> a)
        ;
    cout << "a = " << a << endl;
    cin.clear();
    int b = 0;
    while(cin >> b)
        ;
    cout << "b = " << b;

}

I keyed in a few integral numbers for 'a' first, and then keyed in a random letter, so the first while loop was terminated and the state of 'cin' was set to be 'cin.failbit'. After that, I used the clear member function to turn off the 'failbit', so the state of 'cin' should change back to 'goodbit' and once more ready to be used. Then, I tried to use 'cin' again to input values for 'b', but the program would skip this part and terminate, and what's even worse is that the program outputs of 'a' and 'b' are both 0, even if the last value I keyed in for 'a' is not 0. Could anyone explain why this happen to me? Thanks!
1) inout operators write 0 to target on unsuccesfull write.
2) clear() clears stream state, it does not change its buffer.

Imagine, you have "1 5 43 a 2 6" feeded to cin.
Your program will read numbers including 43, then will try to read 'a' and fails. 0 will be written in variable a and stream will be set to failed state. Sequence "a 2 6" will be in input buffer.
Then you will clear state — without changing buffer — and wwil try to read integer again. 'a' is encountered and reading is failed again, 0 is written to b, etc.
Thanks for the elaborate explanation. One more question though, is the anyway I can flush the buffer of an input object, say 'cin', so that this program would work the way I expect it to be?
1) skips to the end of the line:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
2) skips to the first whitespace character (or until stream end):
1
2
while(!::isspace(std::cin.get()) && std::cin)
    ;
Get it, thanks a lot.
Topic archived. No new replies allowed.