问题
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, and1
: a successfully matched floating-point number that is stored innumber
.
Therefore,
while(scanf("%f", &number) && number > 0)
while(scanf("%f", &number) == 1 && number > 0)
The first
scanf("%f", &number) [!= 0] && ...
will return false on[0]
, true on[EOF, 1]
. On1
, in the case of one variable, it will work as expected, but onEOF
, it proceeds along the short-circuit to read from uninitialised memory; in the next call toscanf
, it will probably hang waiting for input fromstdin
that's (most likely) been closed.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