I compiled and run the following console program which is supposed to read an integer and return the number of field successfully read:
# include <stdio.h>
int main ( void )
{
int result, number;
printf ( "开发者_运维知识库 Enter an integer : \n ");
result=scanf ( " %d " , & number );
printf ( " Fields read % d " , result );
return 0;
}
I compiled ( VS 2008 ) and tested it on 2 machines under Win Vista and while on one machine it runs as expected, in the other case when I enter the number the scanf does not return and waits for additonal input. I have to enter another integer for it to exit and furthermore when it exits it returns 1 as a result value which is incorrect since I entered 2 integers .
Am I missing something ?
The spaces in the conversion specification for scanf mean: "jump over and ignore spaces in input if there's any".
The "%d" in the conversion specification means: "jump over and ignore spaces if there's any, then read an int
"
So, when you say " %d " you are saying: "jump over spaces if any, read an int
, jump over spaces if any, stop".
When you enter a number, this happens:
input: 42<ENTER> scanf: ^^ int scanf: ^^^^^^^ space
And after ignoring the <ENTER>, scanf is still in "ignoring space" mode. It needs to "see" something not a space to "stop".
This is happening because your format string " %d "
has a spaces in it.
Try using "%d"
instead.
精彩评论