YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Working with inputChapter 51 of 73

Formatted input: matching and limits

Read scanf destination contracts, assignment counts, field widths, whitespace behavior, and numeric conversion limits.

6 min readIntermediateC17 baseline
Offline reading
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.

Conversionprintf valuescanf destination
%dintint *
%ldlonglong *
%zusize_tsize_t *
%fdoublefloat *
%lfdoubledouble *
%Lflong doublelong double *
%cintchar *
%sReadable string pointerWritable 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.

C17 · illustrative fragment
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

C17 · illustrative fragment
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

C17 · illustrative fragment
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

C17 · illustrative fragment
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

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.
Explain it in your own words

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.

Why check scanf’s return value before using the result of a counted conversion?
Read the explanation for every choice
  1. 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.

  2. scanf always fills every destination with zero first.

    A failed conversion does not promise to initialize the destination to zero.

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

CHAPTER 51 / 73

In this chapter

Formatted input: matching and limits

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping