当 scanf!=EOF 或 scanf==1 时?
其他条件相同(格式良好的数据、良好的缓冲实践等等),是否有理由让我更喜欢在 scanf
的返回值为 1 时进行循环,而不是 !EOF
?我可能在某处读过这篇文章,或者其他什么,但我也可能有错。其他人怎么看?
Ceteris paribus (well formed data, good buffering practices and what not), is there a reason why I prefer to loop while the return of scanf
is 1, rather than !EOF
? I may have read this somewhere, or whatever, but I may have it wrong as well. What do other people think?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
scanf
返回成功转换的项目数...或 EOF(出错时)。因此,请按照有意义的方式对条件进行编码。人为的示例
编辑:添加了另一个更人为的示例
scanf
returns the number of items succesfully converted ... or EOF on error. So code the condition the way it makes sense.Contrived example
Edit: added another more contrived example
取决于您想要如何处理格式错误的输入 - 如果您的扫描模式不匹配,您可能会返回
0
。因此,如果您在循环之外处理这种情况(例如,如果您将其视为输入错误),则与1
进行比较(或者无论您的 scanf 调用中有多少项)。Depends what you want to do with malformed input - if your scan pattern isn't matched, you can get
0
returned. So if you handle that case outside the loop (for example if you treat it the same as an input error), then compare with1
(or however many items there are in your scanf call).来自 http://www.cplusplus.com/reference/clibrary/cstdio/scanf/< /a>
确保您读取预期项目数的唯一方法是将返回值与该数字进行比较。
From http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
The only way to be sure that you read the number of items intended is to compare the return value to that number.