Re: how to check the scanf function if it will read more than one number
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Mon, 02 Jan 2006 10:44:57 GMT
"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.
.
- Follow-Ups:
- References:
- Prev by Date: Re: gets() - dangerous?
- Next by Date: Re: how to check the scanf function if it will read more than one number
- Previous by thread: Re: how to check the scanf function if it will read more than one number
- Next by thread: Re: how to check the scanf function if it will read more than one number
- Index(es):
Relevant Pages
|