Dec 22, 2009 at 10:14am UTC
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 Dec 22, 2009 at 2:51pm UTC
Dec 22, 2009 at 10:40am UTC
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).
Dec 22, 2009 at 1:58pm UTC
@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 Dec 22, 2009 at 2:01pm UTC
Dec 22, 2009 at 2:49pm UTC
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 Dec 22, 2009 at 2:50pm UTC
Dec 22, 2009 at 5:25pm UTC
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.
Dec 23, 2009 at 3:36pm UTC
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 Dec 23, 2009 at 3:36pm UTC