a problem about istream

hi, i'm reading the chapter on "standard IO library". And i copied below codes, with some little changes, to my IDE.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>

using namespace std;

int main()
{
	int ival;

	while(cin >> ival, !cin.eof())
	{		
		if(cin.good())
		{
			cout << ival << endl;
			continue;
		}
		else
		{
			cout << "error, please input again!" << endl;
			cin.clear(istream::failbit);
			continue;
		}
	}

	return 0;
}


When i run it. if i input an int value, it's OK. but if i input some other type data, such as "!", disaster happens. it will display "error, please input again!" ceaselessly. So i have no chance to input next data. How could this happen?

As i'm a newbie to C++, so would you please explain as explicitly as possible? Gneral explanation is also OK. I'd appreciate anyone's help.
Last edited on
If the stream goes bad, you have to manually change the state back to good.
cin.setstate(std::ios::good);

Also, don't check for eof. When end of file is detected, the stream changes state (to bad or fail, I can't remember).
@kbw

Thanks for your help. But i have tried to
replace
cin.clear(istream::failbit);
with
cin.setstate(cin.good());

The output is the same.

error, please input again!
error, please input again!
error, please input again!
error, please input again!
error, please input again!
......


And i also tried cin.clear(), it doesn't help either.
any further suggestion?
Thank you.
Last edited on
Some additional information:

I try to use
1
2
cin.setstate(cin.good());
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

to manually change the state to good and empty the buffer.
It also fails.
Last edited on
try
1
2
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
what bazzy posted should work. I think you have a dangling new line. I had a simaler problem a while back and used code similar to what bazzy suggested.
Thanks to Bazzy and btripp.
I have tried what Bazzy posted. It works very well.
And now I know the difference between cin.setstate() and cin.clear().
Last edited on
Topic archived. No new replies allowed.