Re: how to check the scanf function if it will read more than one number



"Moosdau" <moosdau@xxxxxxxxx> writes:
> Peter Nilsson wrote:
>> Your implementation probably defines a behaviour fflush on
>> input streams. It would do so as an extension. That extension
>> is not topical in comp.lang.c.
>>
> it do be that.
> I think I've already known the answer.
> the below is I copied from MSDN:
>
> The fflush function flushes a stream. If the file associated with
> stream is open for output, fflush writes to that file the contents of
> the buffer associated with the stream.
> If the stream is open for input, fflush clears the contents of the
> buffer.
>
> Example
> // crt_fflush.c
> #include <stdio.h>
> #include <conio.h>
>
> int main( void )
> {
[snip]
> int integer;
> char string[81];
>
> /* Read each word as a string. */
> printf( "Enter a sentence of four words with scanf: " );
> for( integer = 0; integer < 4; integer++ )
> {
> scanf( "%s", string );
> // Security caution!
> // Beware allowing user to enter data directly into a buffer
> // without checking for buffer overrun possiblity.
> printf( "%s\n", string );
> }

So MSDN shows an example of a possible buffer overflow and provides a
comment that doesn't give you a clue how to avoid it.

> /* You must flush the input buffer before using gets. */
> fflush( stdin ); // fflush on input stream is an extension to the
> C standard
> printf( "Enter the same sentence with gets: " );
> gets( string );
> printf( "%s\n", string );
> }

And the example uses gets() without even warning that it's unsafe.
For nearly all practical purposes, gets() cannot be used safely.

[snip]

> then I know,I shouldn't use fflush(stdin) except in VC.
> but in VC, it is safe.

Here's a better idea: don't use fflush(stdin) at all. Second best:
don't use fflush(stdin) unless you're certain your code will never be
ported to an implementation that doesn't support it.

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.



Relevant Pages