scanf()== 1的用途是什么? [英] What is the use of scanf() == 1?

查看:144
本文介绍了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 :流末尾的负值或读取错误(如果要区分后一种情况,请参见
  • EOF: a negative value for the end of stream or a read error, (if one wants to differentiate the latter case, see ferror(stdin) or !feof(stdin), and on POSIX-conforming systems, errno will be set,)
  • 0: a matching error, and
  • 1: a successfully matched floating-point number that is stored in number.

因此

while(scanf("%f", &number) && number > 0)
while(scanf("%f", &number) == 1 && number > 0)

  1. 第一个 scanf(%f",& number)[!= 0]&&... 将在 [0] 上返回false,在 [EOF,1] 上返回true.在 1 上,对于一个变量,它将按预期工作,但是在 EOF 上,它沿着短路进行以从未初始化的存储器中读取数据.在下一次对 scanf 的调用中,它可能会挂起,等待(很可能已关闭)来自 stdin 的输入.

  1. The first scanf("%f", &number) [!= 0] && ... will return false on [0], true on [EOF, 1]. On 1, in the case of one variable, it will work as expected, but on EOF, it proceeds along the short-circuit to read from uninitialised memory; in the next call to scanf, it will probably hang waiting for input from stdin 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屋!

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