在 while 循环中使用 scanf [英] Using scanf in a while loop
问题描述
对于这个极其简单的问题可能是一个极其简单的答案:
Probably an extremely simple answer to this extremely simple question:
我正在阅读 Pratta 的C Primer Plus",他一直在使用这个例子
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 被评估为假,其他一切都为真.因此,如果 scanf 返回 EOF,这是一个负值,循环将评估为真,这不是您想要的.
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.
这篇关于在 while 循环中使用 scanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!