【发布时间】:2012-05-15 05:26:27
【问题描述】:
我知道scanf函数的签名是:
int scanf(const char *format, ...)
此函数返回的int 值是什么?
【问题讨论】:
-
@Bulwersator 如果有人看不懂手册页,那么这不是此类问题的论坛。在这种情况下,所有编程语言中都可能有 1000 种函数的返回值 XYZ。这个问题缺乏非常基础的研究,不应该被鼓励。
我知道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。
来自scanf:
成功时,函数返回成功读取的项目数。如果发生匹配失败,此计数可以匹配预期的读数数量或更少,甚至为零。 如果在成功读取任何数据之前输入失败,则返回 EOF。
【讨论】:
我认为您的代码无法正常工作,因为您忘记了 scanf 函数中的“&”..
int g=0; //init the variable
int p=scanf("%d",&g);
scanf函数会将输入的值放到g变量地址中。
【讨论】:
从技术上讲,这是 UB(未定义行为)。
int g;
int p=scanf("%d",g);
^
您将一个未初始化的整数传递给 scanf 以将其用作要写入的地址。从这一点开始,任何事情都可能发生。您的应用很可能会崩溃。
【讨论】:
无论您在 VDU 输入中给出什么,都将转到变量 g,如果成功读取,p 等于 1。
【讨论】:
它将返回 1,因为 scanf 返回成功读取的项目数
【讨论】:
bbldnai怎么办?那么它肯定不会返回 1。