Using fscanf() vs. fgets() and sscanf()

后端 未结 3 1767
再見小時候
再見小時候 2020-11-29 06:23

In the book Practical C Programming, I find that the combination of fgets() and sscanf() is used to read input. However, it appears to me that the

3条回答
  •  迷失自我
    2020-11-29 06:43

    The problem with only using fscanf() is, mostly, in error management.

    Imagine you input "51 years, 85 Kg" to both programs.

    The first program fails in the sscanf() and you still have the line to report errors to the user, to try a different parsing alternative, to something;

    The second program fails at years, age is usable, weight is unusable.

    Remeber to always check the return value of *scanf() for error checking.

        fgets(line, sizeof(line), stdin);
        if (sscanf(line, "%d%d", &age, &weight) != 2) /* error with input */;
    

    Edit

    With your first program, after the error, the input buffer is clear; with the second program the input buffer starts with YEAR...

    Recovery in the first case is easy; recovery in the second case has to go through some sort of clearing the input buffer.

提交回复
热议问题