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




Keith Thompson wrote:
> scanf() returns the number of items assigned. If you give it " 32 a ",
> it will assign 32 to dend and fail to assign a value to dor; scanf()
> will then return 1. If you want to assign both values, you need to
> check whether scanf() returned 2.
>
> You should pick a better name than "temp1". The simplest thing to do

sorry,because I copied it from a long code,
if I named every variant with its meaning, there must be too many
temporary variants.
so ......

> is to assign the result of scan() to a variable, and test the value
> of that variable. Pseudo-code follows:
>
> do {
> printf("...\n");
> items_read = scanf(...);
> } while (items_read != 2);
>
> Don't use fflush(stdin). The fflush() function is defined only for
> output streams.


Thanks very much!!
but I don't know very clearly why shouldn't I use the fflush function.
if there is not any usable data in the input stream,
could I use it to clear the input stream?
if not , could you please tell me why?


> scanf() can be very tricky, it can leave unread garbage in your input
> stream, and it can be difficult to figure out just what it's doing. A
> better approach is to use fgets() to read an entire line, then use
> sscanf() to get information from the line you've read.

thanks for your suggestion!


> --
> 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

  • Re: Newbie questions
    ... The infamous '\n' in the scanf format specifier. ... consume the non-whitespace input that you gave but leave it behind in the ... and the next to consume the newline in the input stream. ... To be portable to C89 compilers, ...
    (comp.lang.c)
  • Re: fflush and stdin
    ... int main ... interactive user input. ... character, it will be left in the input stream (for example, if the ... Instead of using scanf() for interactive ...
    (comp.lang.c)
  • Re: how to check the scanf function if it will read more than one number
    ... If you want to assign both values, you need to check whether scanf() returned 2. ... but I don't know very clearly why shouldn't I use the fflush function. ... if there is not any usable data in the input stream, ... and get the next thing the user types, ...
    (comp.lang.c)
  • Re: confused about behaviour of scanf
    ... > It is skipping a scanf function which it should not. ... input stream after the first scanf. ... all numeric characters up to the first non-numeric character. ... the second scanf() is being skipped. ...
    (comp.lang.c)