C Reference ยท stdio.h
scanf pitfalls
The common scanf mistakes in C and their fixes: unbounded %s, leftover newlines, infinite loops on bad input, ignored return values and %lf vs %f.
scanf() is easy to call and hard to use correctly. It mixes reading, converting and parsing in one function, it stops at the first character it dislikes, and it leaves that character in the input. Most of the trouble comes from five things: ignoring the return value, unbounded strings, left-over newlines, loops that never advance, and wrong specifiers.
This page shows each failure and the fix. The fix for most of them is the same: read a line with fgets(), then parse it with sscanf() or strtol().
char line[64]; int n; if (fgets(line, sizeof line, stdin) && sscanf(line, "%d", &n) == 1) { /* ok */ }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
The pitfalls
1. Ignoring the return value
If the input does not match, scanf assigns nothing and returns a smaller count, and your variable keeps whatever it held, often garbage. Always compare the result with the number of conversions you asked for, and initialize the variables.
2. %s without a width
scanf("%s", name) reads as many non-space characters as the user types. Longer than the array means a buffer overflow, which is undefined behavior and exploitable. Always write the maximum: scanf("%31s", name) for char name[32]. The width cannot be passed as an argument (%*s means "skip"), so build the format string or use fgets.
3. The newline that stays behind
scanf("%d", &n) stops after the digits and leaves the '\n' in the input. A later getchar(), scanf("%c", &c) or fgets() reads that newline immediately, so a prompt appears to be skipped. Fix it by consuming the rest of the line (int ch; while ((ch = getchar()) != '\n' && ch != EOF) {}), by using a leading space in " %c", or by reading lines only.
4. Infinite loops on bad input
while (scanf("%d", &n) != 1) { puts("try again"); } loops forever when the user types letters: the failed conversion does not consume the letters, so every retry fails the same way. Discard the offending line inside the loop, or read lines and parse them.
5. Wrong specifier for the type
%f stores a float, so reading into a double requires %lf. %d into a long, or %u into a short, writes the wrong number of bytes. These mistakes are undefined behavior, and GCC warns only when the format is a literal and -Wformat is on.
6. Overflow and trailing text
scanf("%d") on 99999999999 is undefined behavior; there is no range check. 12abc happily returns 12 and leaves abc. strtol reports both problems.
7. %c and whitespace
%c reads the very next character, including a space or newline. Write " %c" to skip whitespace first.
Usage notes
- Prefer
fgets+sscanf/strtol. You keep control of the buffer size, you can print the offending line, and a bad line never poisons the next read. fgetskeeps the newline, so strip it (line[strcspn(line, "\n")] = '\0') if it matters, and detect over-long lines by the missing newline.- Never use
gets(). It was removed in C11 because it cannot be used safely. scanfis acceptable for quick programs, tests and fixed input formats, as long as you check the count and use widths.EOFvs. 0.EOFmeans the stream ended;0means the text did not match. Handle both.- Mixing
scanfwithfgetson the same stream is a source of confusing bugs because of the newline rule above; choose one style per stream.