[英]Can anyone explain the output for scanned value of the following program..?
#include<stdio.h>
int main()
{
int i;
printf("%d\n", scanf("%d", &i) );
return 0;
}
If some value is supplied to scanf()
the output of the program is still 1. Why ? 如果将某些值提供给scanf()
,则程序的输出仍为1。为什么?
if some value is supplied scanf but the output of the program is still 1. Why? 如果提供了scanf某些值,但是程序的输出仍然为1。为什么?
Because scanf
returns an int
as per the documentation . 因为scanf
根据文档返回int
。 scanf
will return the total number of items scanned and assigned successfully. scanf
将返回已成功扫描和分配的项目总数。
In your case, scanf
will return 1 if it was successful in scanning an int
from the stdin
, else it will return 0. It will also return -1
on encountering EOF
. 在您的情况下,如果成功从stdin
扫描int
, scanf
将返回1,否则将返回0。遇到EOF
它还将返回-1
。 Then, this value is printed by the printf
you have. 然后,此值由您拥有的printf
打印。
If you want to print the value of i
, seperate the scanf
and the printf
, ie, use 如果要打印i
的值,请将scanf
和printf
分开,即使用
int i;
scanf("%d", &i)
printf("%d\n", i);
instead of 代替
int i;
printf("%d\n" , scanf("%d", &i) );
In the below statement, 在下面的语句中,
printf("%d\n" , scanf("%d", &i) );
you're not printing the value scanned and stored by scanf()
, you're printing the return value of scanf()
. 您不是要打印scanf()
扫描和存储的值,而是要打印scanf()
的返回值 。
The value, scanned by scanf()
will be stored in the supplied argument, here, the variable i
. 由scanf()
扫描的值将存储在提供的参数中,此处为变量i
。
Remember, scanf()
does not return the scanned value , it returns the number of items it successfully matched and assigned . 记住, scanf()
不返回 扫描值 ,它返回成功匹配并分配的项目数 。
If you want to print the scanned value, you have to use the same variable where the value is stored, ie, i
. 如果要打印扫描的值,则必须使用存储值的相同变量,即i
。
printf("The scanned value is %d\n", i);
That said, as a note, the recommended signature for main()
is int main(void)
. 也就是说,需要注意的是, main()
的推荐签名是int main(void)
。
The return type of scanf()
is number of items of the argument list successfully filled.In your case one item is being read so if successful 1
will be returned by scanf()
Similarly the following would return 2
because there are two items being read. 的返回类型scanf()
是参数列表中的项目成功filled.In你的情况下,一个项目的数量正在读因此,如果成功1
将返回scanf()
类似以下内容将返回2
,因为有被读取两个项目。
int i,j;
printf("%d\n" , scanf("%d %d", &i,&j) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.