在循环使用scanf函数 [英] Using scanf in a while loop
问题描述
大概是一个非常简单的答案,这非常简单的问题:
Probably an extremely simple answer to this extremely simple question:
我在读C的Primer Plus的Pratta,他一直使用的例子
I'm reading "C Primer Plus" by Pratta and he keeps using the example
while (scanf("%d", &num) == 1)...
时的== 1真的有必要吗?这似乎是人们可以这样写:
Is the == 1 really necessary? It seems like one could just write:
while (scanf("%d", &num))
这似乎是平等的测试是不必要的,因为scanf函数的对象读取和1将使while循环真正返回数字。为确保读元素的数量正好是1或者是原因,这完全是多余的?
It seems like the equality test is unnecessary since scanf returns the number of objects read and 1 would make the while loop true. Is the reason to make sure that the number of elements read is exactly 1 or is this totally superfluous?
推荐答案
在C,0被评估为假,一切为true。因此,如果scanf函数返回EOF,这是一个负值,循环将评估为true,这是你想要不是什么。
In C, 0 is evaluated to false and everything else to true. Thus, if scanf returned EOF, which is a negative value, the loop would evaluate to true, which is not what you'd want.
这篇关于在循环使用scanf函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!