Using scanf in a while loop

前端 未结 5 910
庸人自扰
庸人自扰 2020-12-11 01:49

Probably an extremely simple answer to this extremely simple question:

I\'m reading \"C Primer Plus\" by Pratta and he keeps using the example

while          


        
5条回答
  •  伪装坚强ぢ
    2020-12-11 02:25

    Since scanf returns the value EOF (which is -1) on end of file, the loop as written is correct. It runs as long as the input contains text that matches %d, and stops either at the first non-match or end of file.

    It would have been clearer at a glance if scanf were expecting more than one input....

    while (scanf("%d %d", &x, &y)==2) { ... }
    

    would exit the loop when the first time it was unable to match two values, either due to end of file end of file (scanf returns EOF (which is -1)) or on input matching error (e.g. the input xyzzy 42 does not match %d %d so scanf stops on the first failure and returns 0 without writing to either x or y) when it returns some value less than 2.

    Of course, scanf is not your friend when parsing real input from normal humans. There are many pitfalls in its handling of error cases.

    Edit: Corrected an error: scanf returns EOF on end of file, or a non-negative integer counting the number of variables it successfully set.

    The key point is that since any non-zero value is TRUE in C, failing to test the return value correctly in a loop like this can easily lead to unexpected behavior. In particular, while(scanf(...)) is an infinite loop unless it encounters input text that cannot be converted according to its format.

    And I cannot emphasize strongly enough that scanf is not your friend. A combination of fgets and sscanf might be enough for some simple parsing, but even then it is easily overwhelmed by edge cases and errors.

提交回复
热议问题