Formatted input: matching and limits
Read scanf destination contracts, assignment counts, field widths, whitespace behavior, and numeric conversion limits.
In this chapter8 sections
Formatted input tries to match text to a requested pattern. A call can match only part of the input or assign fewer values than expected. Understanding its return result and destination limits is essential before relying on the values.
1. Input needs destinations, not the output argument types
scanf reads stdin, fscanf a selected stream, and sscanf a null-terminated input string. They share input-conversion rules. A scalar destination usually needs its address, such as &number. An array name normally converts to a pointer to its first element, so a character array used with %s is passed as word, not &word.
| Conversion | printf value | scanf destination |
|---|---|---|
%d | int | int * |
%ld | long | long * |
%zu | size_t | size_t * |
%f | double | float * |
%lf | double | double * |
%Lf | long double | long double * |
%c | int | char * |
%s | Readable string pointer | Writable character array with sufficient space |
A destination with the wrong type, insufficient storage, or ended lifetime violates the contract. The variadic interface does not supply a hidden buffer size. printf’s float-to-double promotion does not transform a float pointer into a double pointer for scanf. Include <stdio.h> for the declarations.
int number = 0;
char word[4];
int assigned = sscanf("12 cat", "%2d %3s", &number, word);
The two numeric input characters in this controlled example are safely representable as int. %3s stores at most three non-whitespace characters plus a terminator, so the array needs four elements. Successful assignments are counted; use results only after checking the expected count. A partial match can already have modified earlier destinations, so initialize temporary parse objects when the caller needs all-or-nothing updates.
2. A field width limits consumption, not the entire record
char first[4];
char second[4];
int assigned = sscanf("codedile", "%3s%3s", first, second);
The first conversion leaves the rest of the word available to the next conversion. This is useful when parsing a specified layout, but a width-limited %s call is not proof that the user supplied a short enough word. A remaining suffix can become the next field or the next input attempt. For %c, a width requests that many characters and adds no null terminator; %[ also needs an appropriate width and room for its terminator.
3. Whitespace in the format is an instruction
char first = '?';
char second = '?';
int a = sscanf(" x", "%c", &first);
int b = sscanf(" x", " %c", &second);
Most conversions skip leading input whitespace; %c, %[, and %n are exceptions. Whitespace in the format consumes any amount of input whitespace, including newlines, until the next non-whitespace character or the end of input. Therefore scanf("%d\n", &number) is not simply “read an integer and finish its line”: an interactive call may keep waiting for a later non-whitespace character. A literal comma or other ordinary format character must match the corresponding input.
4. Separate matching failure from input failure
int value = 99;
int mismatch = sscanf("cat", "%d", &value);
int input_end = sscanf("", "%d", &value);
int assigned = sscanf("12 34", "%*d %d", &value);
A matching failure means available input does not fit the conversion, as with cat for %d. An input failure means input could not be obtained, for example because of end-of-input or a read error. EOF is returned for input failure before the first conversion has completed; otherwise the return is the number of assignments, which can be zero. Assignment-suppressed conversions such as %*d do not increase that count. The special %n conversion normally stores the number of characters consumed so far, but its assignment is excluded from the returned count.
A matching failure can leave the troublesome character unread. Repeating the same call without consuming or replacing that input can repeat the same failure forever. On a stream, inspect its error/end indicators after the input operation reports failure. This is another reason that acquiring a whole bounded line before parsing gives an interactive program a clearer retry boundary.
5. Representability is still your responsibility
C17 specifies undefined behavior if a numeric scanf result cannot be represented in the destination object. Checking a return count afterward cannot repair that event. A field width merely bounds characters; many digits can still exceed a destination’s range, and a user can supply a token longer than the chosen width. Prefer bounded line acquisition followed by strtol/strtoul or another suitable checked conversion for external numeric text.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 7.21.6.2, 7.21.6.4, 7.21.6.7, 7.21.10. Stable core provisions used for the C17 baseline; not the final ISO publication.
- WG14 N3096 — public C23 working draft: 7.23.6.2. C23 notes are source-reviewed separately from C17 example checks.
Before you move on
- Formatted input can stop after a partial match or a failed conversion.
- Destination types and field widths must match the conversion contract and available storage.
- Numeric input whose converted value cannot be represented needs particular care with scanf-family rules.
Keep these ideas separate
- Characters consumed / Values assigned
- A call can consume input without assigning the number of destinations you expected; inspect its result.
Why is a successful first conversion insufficient evidence that the whole requested input record was accepted?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- An input conversion can fail before storing that result.
✓ Correct reasoning. Check the expected number of counted assignments before using the results; %n is excluded from that count.
- scanf always fills every destination with zero first.
A failed conversion does not promise to initialize the destination to zero.
- A width limit guarantees valid numeric range.
A field width limits consumed input; it is not a general numeric-range validation strategy.
C17
Ready for the next idea?
Mark this chapter as read whenever you feel ready.