在 while 循环中使用 scanf [英] Using scanf in a while loop

查看:36
本文介绍了在 while 循环中使用 scanf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于这个极其简单的问题可能是一个极其简单的答案:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆