[Subject Prev][Subject Next][Thread Prev][Thread Next][Subject Index][Thread Index]

Re: Re: Re: Fw: Infinite Joy Ride(example)



Rahul Jindal forced the electrons to say:
> >         characters it encounters terminate the conversion *and are left
> >         on the input stream*.  Therefore, unless some other steps are
> >         taken, unexpected non-numeric input "jams" scanf() again and
> >         again: scanf() never gets past the bad character(s) to encounter
> 
> but even flushing the stream didn't help him.

Well, I'm back on LIP, after a 2 week hiatus...

There is no such thing as flushing an input stream. The operation
(fflush (stdin)) will invoke undefined behaviour. Don't use it.

A loop like 

while (getc(stdin) != '\n')
    /* do nothing */;

will simulate flushing the input stream. It is not recommended,
though, since you might lose data. It is far better to fgets() lines
from stdin and hand-parsing them. Or maybe use a tool like lex if the
program requires it.

To the OP: I read the problem you posed in the archives. When you
input a character while your program was expecting an int, the result
was an infinite loop. You were using scanf() to read input.

When scanf() cannot make a successful assignment, it pushes back the
extra bytes it read to the input stream. Since you were using scanf in
a loop, the first 'A' you entered was repeatedly pushed back, only so
that the next scanf choked on it.

I'd suggest you use a combination of fgets() and atoi().

Binand