Re: cin error recovery

From: E. Robert Tisdale (E.Robert.Tisdale_at_jpl.nasa.gov)
Date: 02/08/04


Date: Sat, 07 Feb 2004 22:29:50 -0800

Roman Gavrilov wrote:

>
> while (true) {
> int i1;
> cin >> i1;
> cout << i1;
> }
>
> if in the snippet above
> I enter error once, it will output the "weird" value forever.

Of course. That's what it's supposed to do. Try this:

> cat main.cc
         #include <iostream>

         int main(int argc, char* argv[]) {
           int i1 = 666;
           while (std::cin >> i1) {
             std::cout << i1 << std::endl;
             }
           std::cout << i1 << std::endl;
           return 0;
           }

> g++ -Wall -ansi -pedantic -o main main.cc
> ./main
         www
         666
> ./main
         777
         777
         www
         777

The input function

        istream& operator>>(istream&, int&)

looks at the first character of "www" and knows that
it can't be part of an int so it returns with i1 unchanged.
It doesn't actually read any characters so "www"
will still be there the next time that you try to read.
Notice that if I enter 777 operator>> succeeds
and i1 is set to 777.