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