I have very frequently seen people discouraging others from using scanf
and saying that there are better alternatives. However, all I end up seeing is either
What can I use to parse input instead of scanf?
Instead of scanf(some_format, ...)
, consider fgets()
with sscanf(buffer, some_format_and %n, ...)
By using " %n"
, code can simply detect if all the format was successfully scanned and that no extra non-white-space junk was at the end.
// scanf("%d %f fred", &some_int, &some_float);
#define EXPECTED_LINE_MAX 100
char buffer[EXPECTED_LINE_MAX * 2]; // Suggest 2x, no real need to be stingy.
if (fgets(buffer, sizeof buffer, stdin)) {
int n = 0;
// add -------------> " %n"
sscanf(buffer, "%d %f fred %n", &some_int, &some_float, &n);
// Did scan complete, and to the end?
if (n > 0 && buffer[n] == '\0') {
// success, use `some_int, some_float`
} else {
; // Report bad input and handle desired.
}