What is the use of scanf() == 1?

六月ゝ 毕业季﹏ 提交于 2021-01-28 12:01:07

问题


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.

This is not appropriate since we have an error at the scan process then and the condition should be false or 0.




回答2:


In this case, scanf, will return one of three int values.

  • 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.

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]. 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.

  2. 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.

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.



来源:https://stackoverflow.com/questions/60675068/what-is-the-use-of-scanf-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!