I wrote this code:
char str[10];
whil开发者_C百科e(1)
{
scanf("%d",str);
}
if given a char
('a' for example) the loop just keep on going without stopping and asking for more input (the scanf isn't blocking suddenly)
why is that? :-)
Because a
is not a decimal integer. scanf will attempt to read it but fail and not advance it's internal pointer, thus it will endlessly try to read the same a
as a decimal and fail.
consider the following program:
int d;
char c;
scanf("%d", &d);
scanf("%c", &c);
if you enter a
the first scanf will fail and the second will read 'a
' into c
. This should explain the problem :)
Because it cannot coerce the 'a'
into an integer form, so it "puts it back in the stream" (there's no actual stream here, just a manner of speech). Then your endless loop causes it to try the same routine again. Endlessly.
Your format string is %d
not %s
. Scanf()
is looking for an integer, not a string. Your loop keeps going forever because it says while(1)
so it never ends regardless.
It might be trying to read an int
, but then it notices there is no int in the data stream, so it returns immediately. If it doesn't consume the input stream, then it'll repeatedly do that.
input buffer has a....
your scanf
tries to read an int:
a.... ^ oops : cannot be int. stop scanfing
and on the next loop the a
is still there.
scanf
is notoriously difficult to use correctly, but you must always check its return value:
int chk;
chk = scanf(...); /* pseudo-code */
if (chk != EXPECTED_VALUE) { /* HANDLE ERROR! */ }
To fix this, you need to check to make sure scanf() actually read the value(s) you want. scanf() returns the number of items successfully read. So store the return value, check to see if it's 1. If it's 0, then 0 items were read and you need to empty the stream before trying again. (edit: Well, maybe not necessarily empty it, but at least get past the offending data that's in the stream)
As the others have said, it tries to read an integer, sees 'a'
, fails to read the integer, but then the 'a'
is still in the stream when you try again.
精彩评论