当使用scanf时,返回的值是什么:
int g;
int p = scanf("%d", &g); // Originally: int p = scanf("%d", g);
我知道 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
。
scanf()
函数返回成功扫描和分配的项目数。如果格式字符串为"%s %d %f %*s%n %d"
,则如果一切正常,它将返回4。%*s
抑制赋值,因此不计入数量,而%n
返回偏移量,也不计入数量。如果返回0、1、2或3,则表示出现了错误。只有当没有数据可读取或存在输入错误(不是格式错误,而是“硬件”错误)时,才会返回EOF。使用"%d"
格式时,只有一个转换,因此您将得到EOF
、0
或1
。 - Jonathan Leffler来自scanf:
如果成功,该函数返回成功读取的项数。 这个计数可以与预期读取的数量匹配或更少,甚至为零,如果发生匹配失败。 在任何数据能够成功读取之前出现输入失败的情况下,将返回EOF。
从技术上讲,这是UB(未定义行为)。
int g;
int p=scanf("%d",g);
^
你将一个未初始化的整数传递给scanf,以将其用作要写入的地址。从这一点开始,任何事情都可能发生。最有可能的是你的应用程序会崩溃。
bbldnai
呢?这时它就不会返回 1 了。 - S.S. Anne