开发者

Strange output on using scanf

#include <cstdio>  

int main()  
{  
    int i;
    printf("%d", scanf("%d", &i));
}

Whatever number i input, i 开发者_Python百科get the output:

1

Why is it so?


On success, the scanf function

returns the number of items successfully read.

This count can match the expected number of readings or fewer, even zero, if a matching failure happens. In the case of an input failure before any data could be successfully read, EOF is returned.

Try this as well:

printf("%d",scanf("%d%d",&i,&i));


You output the result of scanf, which is not the number you enter, but the number of items that are successfully read. The number you enter is stored in i. To output it you would have to write an additional line:

#include <cstdio>  

int main()  
{  
   int i;
   if (scanf("%d",&i) == 1)
       printf("%d", i);
}


scanf() returns the number of items read when it succeeds. Here its reading only one number hence the output is 1 every time regardless of the number.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜