我正在遵循C Primer Plus的说明并组成以下代码:
#include <stdio.h>
int main(void) {
int num;
int x = scanf("%d", &num);
printf("%d", x);
}
运行时:
$ ./a.out
t
0
$ ./a.out
2
1
scanf如何检测到“ 0”或“ 1”的值?
答案 0 :(得分:5)
它不会检测到该值,而是将其返回。它读取一个整数并将其放入num
中。 scanf
的返回值不是它从用户输入中读取的值,而是读取的值数,在您的情况下,最大为1。
答案 1 :(得分:4)
scanf
被定义为
成功时,该函数返回成功读取的项目数。如果发生匹配失败,则此计数可以匹配预期的读数数或更少,甚至零。如果在输入数据失败之前无法成功读取任何数据,则返回EOF。
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.