James Kanze
10/7/2008 11:27:00 AM
On Oct 6, 5:25 pm, bbmmzz <bumanz...@gmail.com> wrote:
> Here is my program:
> int main()
> {
> int ival;
> while(cin >> ival, !cin.eof())
Could you please explain what this is supposed to do?
ios::eof() really doesn't have any usable meaning until you know
that an input has failed. It can return true even if the input
succeeds.
The standard idiom for a loop would be:
while ( std::cin >> ival ) ...
If you really want to put the error handling in the loop (which
I'm not sure is a good idea), you can do something like:
while ( std::cin >> ival || ! std::cin.eof() ) ...
(Note that in this case, you will only look at eof if the input
fails.)
> {
> if(cin.bad())
> return 0;
> if(cin.fail())
> {
> cerr << "retry!" << endl;
> cin.clear();
> continue;
> }
> cout << ival << endl;
> }
> return 0;
> }
> Input int number, the program work well. But if input char, example
> 'a', it display "retry!" endless.
> "cin >> ival" is skip after input 'a'? Why?
What did you do with the 'a'? I don't see where you extracted
it.
(Also, returning from the middle of a loop or using continue is
generally a sign of a poor program.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34