scanf()== 1的用途是什么? [英] What is the use of scanf() == 1?
问题描述
我的代码:
while(scanf("%f", &number) && number > 0)
while(scanf("%f", &number) == 1 && number > 0)
这 == 1
是什么,这是必需的吗?
What does this == 1
and is this necessary?
推荐答案
在这种情况下,scanf
,将返回三个 int
值之一.
In this case, scanf
, will return one of three int
values.
-
EOF
:流末尾的负值或读取错误(如果要区分后一种情况,请参见!feof(stdin)
,在符合POSIX的系统上,errno
设置) -
0
:匹配错误,并且 -
1
:一个成功匹配的浮点数,存储在number
中.
EOF
: a negative value for the end of stream or a read error, (if one wants to differentiate the latter case, seeferror(stdin)
or!feof(stdin)
, and on POSIX-conforming systems,errno
will be set,)0
: a matching error, and1
: a successfully matched floating-point number that is stored innumber
.
因此
while(scanf("%f", &number) && number > 0)
while(scanf("%f", &number) == 1 && number > 0)
-
第一个
scanf(%f",& number)[!= 0]&&...
将在[0]
上返回false,在[EOF,1]
上返回true.在1
上,对于一个变量,它将按预期工作,但是在EOF
上,它沿着短路进行以从未初始化的存储器中读取数据.在下一次对scanf
的调用中,它可能会挂起,等待(很可能已关闭)来自stdin
的输入.
The first
scanf("%f", &number) [!= 0] && ...
will return false on[0]
, true on[EOF, 1]
. On1
, in the case of one variable, it will work as expected, but onEOF
, it proceeds along the short-circuit to read from uninitialised memory; in the next call toscanf
, it will probably hang waiting for input fromstdin
that's (most likely) been closed.
第二个 scanf(%f",& number)== 1&&...
将在 [EOF,0]
上返回false,在 [1]
上返回true.这明确确认在继续下一条语句之前已写入变量.这更健壮,将处理匹配和读取错误,并正确处理第二个谓词以检查它是否在域中.
The second scanf("%f", &number) == 1 && ...
will return false on [EOF, 0]
, true on [1]
. This explicitly confirms that the variable has been written before continuing to the next statement. This is more robust and will take care of matching and read errors together, and works properly proceeding to the second predicate to check if it's in the domain.
但是,它没有记录循环停止的原因,并且随后的读取可能有问题.要获得该信息,可以将一个变量分配给 scanf
的返回值.
However, it doesn't record why the loop stopped, and subsequent reads may have problems. To get that information, one could assign a variable to the return value of scanf
.
这篇关于scanf()== 1的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!