简体   繁体   English

scanf() == 1 有什么用?

[英]What is the use of scanf() == 1?

My Code:我的代码:

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

What does this == 1 and is this necessary?== 1是什么,这是必要的吗?

As, Weather Vane said in the comments , the ==1 is important if scanf() returns EOF (End Of File or -1) which would be evaluated to true and since the value in number remains unchanged from the previous iteration the condition of the while loop would be evaluated to true .正如Weather Vane评论中所说,如果scanf()返回EOF (文件结尾或 -1),则==1很重要,这将被评估为true并且由于number的值与前一次迭代保持不变,因此while循环将被评估为true

This is not appropriate since we have an error at the scan process then and the condition should be false or 0 .这是不合适的,因为我们在扫描过程中出现错误,条件应该是false0

In this case, scanf , will return one of three int values.在这种情况下, scanf将返回三个int值之一。

  • 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,) EOF :流结束或读取错误的负值,(如果想区分后一种情况,请参阅ferror(stdin)!feof(stdin) ,并且在符合 POSIX 的系统上,将设置errno ,)
  • 0 : a matching error, and 0 :匹配错误,以及
  • 1 : a successfully matched floating-point number that is stored in number . 1 : 一个成功匹配的浮点数,存储在number

Therefore,所以,

while(scanf("%f", &number) && number > 0)
while(scanf("%f", &number) == 1 && number > 0)
  1. The first scanf("%f", &number) [!= 0] && ... will return false on [0] , true on [EOF, 1] .第一次scanf("%f", &number) [!= 0] && ...将在[0]上返回 false ,在[EOF, 1]上返回 true 。 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;1 ,在一个变量的情况下,它将按预期工作,但在EOF ,它沿着短路继续从未初始化的内存中读取; in the next call to scanf , it will probably hang waiting for input from stdin that's (most likely) been closed.在下一次调用scanf ,它可能会挂起,等待来自stdin输入的输入(很可能)已关闭。

  2. The second scanf("%f", &number) == 1 && ... will return false on [EOF, 0] , true on [1] .第二个scanf("%f", &number) == 1 && ...将在[EOF, 0]上返回 false ,在[1]上返回 true 。 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.这更健壮,将处理匹配和读取错误,并正常工作,继续处理第二个谓词以检查它是否在域中。

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的返回值分配一个变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM