Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
scanf函数返回什么?_C_Scanf - Fatal编程技术网

scanf函数返回什么?

scanf函数返回什么?,c,scanf,C,Scanf,我知道scanf函数的签名是: int scanf(const char *format, ...) 此函数返回的int值是多少?来自man页面: NAME scanf, fscanf, sscanf, vscanf, vsscanf, vfscanf ... RETURN VALUE These functions return the number of input items successfully matched a

我知道
scanf
函数的签名是:

int scanf(const char *format, ...)

此函数返回的
int
值是多少?

来自
man
页面:

NAME
       scanf,  fscanf, sscanf, vscanf, vsscanf, vfscanf 

       ...

RETURN VALUE
       These functions return the number of input items  successfully  matched
       and assigned, which can be fewer than provided for, or even zero in the
       event of an early matching failure.

       The value EOF is returned if the end of input is reached before  either
       the  first  successful conversion or a matching failure occurs.  EOF is
       also returned if a read error occurs, in which case the error indicator
       for  the  stream  (see ferror(3)) is set, and errno is set indicate the
       error.
在您的情况下,
scanf()
可以从以下位置返回
0
1
EOF

成功时,函数返回成功读取的项目数。如果发生匹配失败,此计数可以匹配预期的读数数或更少,甚至为零。 如果在成功读取任何数据之前输入失败,则返回EOF


我认为您的代码无法正常工作,因为您忘记了scanf函数中的“&”

int g=0; //init the variable
int p=scanf("%d",&g);
scanf函数将把输入的值放入g变量地址。

从技术上讲,这是UB(未定义的行为)


将一个单位化整数传递给scanf,以将其用作写入地址。从这一点开始,任何事情都可能发生。你的应用程序很可能会崩溃。

无论你在VDU输入中给出什么,都会进入变量
g
,如果成功读取,
p
等于1。

当scanf返回成功读取的项目数时,它将返回1

为什么您认为该变量需要初始化?@Bulwersator如果有人无法阅读手册页,那么这不是讨论此类问题的论坛。在这种情况下,在所有编程语言中,函数XYZ的返回值可能为1000。这个问题缺乏基础研究,不应该鼓励。返回成功扫描和分配的项目数。如果格式字符串为
“%s%d%f%*s%n%d”
,则如果一切正常,则返回4。
%*s
禁止赋值,因此它不被计数,
%n
返回一个偏移量并且不被计数。如果得到0、1、2或3,则表示出现了问题。只有在没有数据可读取或存在输入错误(不是格式错误,而是“硬件”错误)时,才能返回EOF。对于
%d”
格式,只有一次转换,因此您将获得
EOF
0
1
。如果有人输入
bbldnai
,该怎么办?那么它肯定不会返回1。问题(错误)已被编辑,因此现在所有答案都无效。
int g;
int p=scanf("%d",g);
                 ^