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



"moosdau" <moosdau@xxxxxxxxx> writes:
> my code:
> do
> {
> printf("please input the dividend and the divisor.\n");
> if(!scanf("%d%d",&dend,&dor))
> {
> temp1=1;
> fflush(stdin);
> }
> else
> temp1=0;
> }while(temp1==1);
>
> it seems that it only depend on the first number it read.
> if I input " a 32 ", it could know there is a error,
> but if I input " 32 a ",
> it accept that.

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

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.

--
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: slurping in binary data
    ... I'm very interested in c/fortran interop, and one of the things that you ... for which there's no scanf() equivalent. ... what if fgets() malfunctions and returns a ... before it is used by sscanf(). ...
    (comp.lang.c)
  • Re: Input Verification
    ... >Additionally, despite having read my documentation for scanf(), I'm ... int verify_input ... it off beforehand) if you're getting input from fgets(). ... terminates the valid input immediately. ...
    (comp.lang.c)
  • Re: Input Verification
    ... I'd like to verify that my supplied input is alphanumeric. ... Additionally, despite having read my documentation for scanf(), I'm uncertain how --if it's even possible-- to have a variable input width. ... By taking your advise and using fgets(), I don't think it took me more ... need scanfparsing, use sscanfon the line you got from fgets. ...
    (comp.lang.c)
  • Re: gets, fgets, scanf none is safe...
    ... gets, fgets, scanf leads to buffer overflow... ... None of the above will lead to buffer overflow if used correctly. ... fgets() can do anything that getscan and in a safer manner. ...
    (comp.lang.c)
  • Re: Programmer wannabee question about sscanf
    ... By using fgetsand sscanf(), you divide the task into two parts: ... scanf() consumes a variable number of characters from stdin, ... By contrast, fgets() consumes an entire line, including the trailing ...
    (comp.lang.c)