Formatted input in K&R C
last modified December 5, 2026 K&R C 1978
scanf is the input counterpart of printf. It
reads characters from the standard input, converts them under the control
of a format string, and stores the results. Its conversions look like
those of printf, but there are
differences in the details, and most of the trouble with
scanf comes from input that does not match the format. This
article shows how to detect such input and recover from it.
Reading a value
scanf must store the values it reads in the caller's
variables. A C function cannot change its arguments, so the caller passes
the addresses of the variables, as the pointers
article explains.
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
printf("twice %d is %d\n", n, 2 * n);
return 0;
}
%d skips blanks, tabs, and newlines, reads a decimal number,
and stores it through the pointer &n. Forgetting the
& is the classic mistake with scanf: the
function then takes the value of n for an address and stores
the number somewhere else in memory.
$ gcc -std=c89 -pedantic -Wall -Wextra -o twice twice.c $ echo 21 | ./twice twice 21 is 42
The return value
scanf returns the number of values it has converted and
stored. At the end of the input it returns EOF. A loop that
reads numbers until there are no more tests the result.
#include <stdio.h>
int main()
{
int n, count, sum;
count = sum = 0;
while (scanf("%d", &n) == 1) {
count++;
sum += n;
}
printf("%d numbers, sum %d\n", count, sum);
return 0;
}
Each call reads one number, and the loop continues as long as one value was
stored. The numbers may be spread over the lines in any way, because
%d skips newlines like any other white space. A plus sign is
accepted as well as a minus sign.
$ gcc -std=c89 -pedantic -Wall -Wextra -o sum sum.c $ printf '12 -7 30\n+5 100\n' | ./sum 5 numbers, sum 140
Failed matches
When the input does not fit the conversion, scanf stops and
returns the number of values stored so far. The character that did not
match is not consumed; it stays in the input for the next read.
#include <stdio.h>
int main()
{
int i, n, r;
n = 0;
for (i = 0; i < 6; i++) {
r = scanf("%d", &n);
printf("scanf returned %2d, n = %d\n", r, n);
if (r == EOF)
break;
}
return 0;
}
The first two calls read 10 and 20 and return 1. The third call meets the
a of apples, stores nothing, and returns 0;
n keeps its old value. Every further call meets the same
a again. A loop that only tests for EOF never
ends on such input, which is why this program stops after six calls. The
number 30 is never reached.
$ gcc -std=c89 -pedantic -Wall -Wextra -o results results.c $ echo '10 20 apples 30' | ./results scanf returned 1, n = 10 scanf returned 1, n = 20 scanf returned 0, n = 20 scanf returned 0, n = 20 scanf returned 0, n = 20 scanf returned 0, n = 20
Skipping bad input
To get past the bad input, the program must read it in another way. After
a failed match, the next program reads the rest of the word with
getchar and goes on.
#include <stdio.h>
/* skip the rest of a word that is not a number */
int skip_word()
{
int c;
while ((c = getchar()) != EOF && c != ' ' && c != '\t' && c != '\n')
putchar(c);
return c;
}
int main()
{
int n, r, sum;
sum = 0;
while ((r = scanf("%d", &n)) != EOF) {
if (r == 1) {
sum += n;
continue;
}
printf("skipped '");
skip_word();
printf("'\n");
}
printf("sum %d\n", sum);
return 0;
}
The loop ends only at EOF. When scanf returns 0,
skip_word reads and prints the characters up to the next
white space. In 5kg, the 5 is a number and is added; only
kg is skipped.
$ gcc -std=c89 -pedantic -Wall -Wextra -o skipbad skipbad.c $ echo '10 20 apples 30 5kg 7' | ./skipbad skipped 'apples' skipped 'kg' sum 72
Literal characters
Ordinary characters in the format string must match the same characters in
the input. A blank or tab in the format matches any amount of white space,
including none. Conversions other than %c skip white space
before their value anyway.
#include <stdio.h>
int main()
{
int r, month, day, year;
while ((r = scanf("%d/%d/%d", &month, &day, &year)) == 3)
printf("day %d of month %d in %d\n", day, month, year);
printf("scanf returned %d\n", r);
return 0;
}
The format %d/%d/%d reads a date written with slashes. The
input has three dates on two lines. The third one has a blank after a
slash, which %d skips. At the end, scanf returns
EOF, which is -1. A date with another separator, such as
12-25-1978, would stop the loop with a return value of 1.
$ gcc -std=c89 -pedantic -Wall -Wextra -o dates dates.c $ printf '12/25/1978\n1/1/1979 3/ 4/1980\n' | ./dates day 25 of month 12 in 1978 day 1 of month 1 in 1979 day 4 of month 3 in 1980 scanf returned -1
Conversion characters
The conversion characters are those of printf:
d, o, and x for integers,
e and f for floating-point numbers,
c for a character, and s for a string. The
arguments are pointers, and the conversion must name the exact type the
pointer points to: an l before d,
o, or x means a pointer to long,
and before e or f a pointer to
double.
#include <stdio.h>
int main()
{
unsigned oct, hex;
int n;
long big;
float f;
double d;
char word[20];
n = scanf("%o %x %ld %f %lf %s", &oct, &hex, &big, &f, &d, word);
printf("%d values\n", n);
printf("oct %u, hex %u, big %ld\n", oct, hex, big);
printf("f %g, d %g, word %s\n", f, d, word);
return 0;
}
%o reads 777 as octal, 511, and %x reads
ff as 255. %f stores a float and
%lf a double. This is a difference from
printf, which receives every float argument as a
double and prints both with %f; a pointer is not
converted, so scanf must know the size of the variable.
%s reads a word up to the next white space and stores it with
a null character at the end. An array name is already an address, so
word needs no &.
$ gcc -std=c89 -pedantic -Wall -Wextra -o convs convs.c $ echo '777 ff 100000 2.5 0.1 tape-reel' | ./convs 6 values oct 511, hex 255, big 100000 f 2.5, d 0.1, word tape-reel
Wrong pointer types
Like printf, scanf cannot see the types of its
arguments. A conversion that does not match the variable stores the wrong
number of bytes in the wrong format.
#include <stdio.h>
int main()
{
double d;
long big;
d = 0;
big = 0;
scanf("%f %d", &d, &big);
printf("d = %g, big = %ld\n", d, big);
return 0;
}
%f stores a four-byte float into the first half of
the eight-byte double. On x86-64, an IEEE double
keeps its exponent in the other half, so the result is a tiny number.
%d stores four bytes into the eight-byte long,
and because x86-64 puts the low-order bytes first, the value comes out
right: the error stays hidden until a number does not fit in four bytes.
GCC warns about both lines.
$ gcc -std=c89 -pedantic -Wall -Wextra -o wrongtyp wrongtyp.c
wrongtyp.c: In function ‘main’:
wrongtyp.c:10:13: warning: format ‘%f’ expects argument of type ‘float *’, but argument 2 has type ‘double *’ [-Wformat=]
10 | scanf("%f %d", &d, &big);
| ~^ ~~
| | |
| | double *
| float *
| %lf
wrongtyp.c:10:16: warning: format ‘%d’ expects argument of type ‘int *’, but argument 3 has type ‘long int *’ [-Wformat=]
10 | scanf("%f %d", &d, &big);
| ~^ ~~~~
| | |
| int * long int *
| %ld
$ echo '2.5 100' | ./wrongtyp
d = 5.31535e-315, big = 100
On the PDP-11 the results are the other way round. A float is
the first half of a double in the same format, so the
double receives 2.5, correct to the precision of a
float. A long keeps its high-order word first,
so the 100 lands in the high word and the value is 100 × 65536 =
6553600.
$ cc wrongtyp.c $ echo '2.5 100' | a.out d = 2.5, big = 6553600
Widths, characters, and suppression
A number after the % is the maximum field width: the
conversion reads at most that many characters. %c reads the
next character, white space included. A * after the
% reads and converts a field but does not store it; this
assignment suppression skips parts of the input.
#include <stdio.h>
int main()
{
int year, month, day, value;
char c, code[4];
scanf("%4d%2d%2d", &year, &month, &day);
printf("%d-%d-%d\n", year, month, day);
scanf("%c", &c);
printf("%%c read the code %d\n", c);
scanf(" %c", &c);
printf("' %%c' read '%c'\n", c);
scanf("%3s%*s", code);
printf("%%3s read \"%s\"\n", code);
scanf("%*s %d", &value);
printf("value %d\n", value);
return 0;
}
The widths cut the digits 19781225 into a year, a month, and
a day. The following %c reads the blank after the date, code
32; a blank in front of it, " %c", skips the white space first
and reads the K. %3s reads at most three
characters, which protects a small array, and %*s throws away
the rest of the word. The last call skips the label price:
and reads the number.
$ gcc -std=c89 -pedantic -Wall -Wextra -o fields fields.c $ echo '19781225 K ABCDEF price: 42' | ./fields 1978-12-25 %c read the code 32 ' %c' read 'K' %3s read "ABC" value 42
Scanning a string
sscanf takes a string as its first argument and reads from
it instead of from the standard input. A program can read a whole line,
then try to convert it, and report a bad line without losing its place in
the input. The program reads records of a name, a quantity, and a
price.
tape 12 18.50 disk 2 295 ribbon thirty 4.25 terminal 1 1450.00 printer
The third line has a word instead of a number, and the fifth line has only a name.
#include <stdio.h>
#define MAXLINE 100
int get_line(s, lim)
char s[];
int lim;
{
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
s[i] = c;
if (c == '\n') {
s[i] = c;
i++;
}
s[i] = '\0';
return i;
}
int main()
{
char line[MAXLINE], name[MAXLINE];
int lineno, qty, n;
double price, total;
lineno = 0;
total = 0;
while (get_line(line, MAXLINE) > 0) {
lineno++;
n = sscanf(line, "%s %d %lf", name, &qty, &price);
if (n != 3) {
fprintf(stderr, "line %d: bad record (%d fields)\n", lineno, n);
continue;
}
printf("%-10s %3d x %8.2f\n", name, qty, price);
total += qty * price;
}
printf("total %.2f\n", total);
return 0;
}
get_line is the function from the
arrays article. Every line goes to
sscanf, which fails on a bad line, and the next line starts
fresh. With scanf, the word thirty would remain
in the input and spoil the next record. The messages go to the standard
error with their line numbers.
$ gcc -std=c89 -pedantic -Wall -Wextra -o stock stock.c $ ./stock < stock.txt tape 12 x 18.50 disk 2 x 295.00 line 3: bad record (1 fields) terminal 1 x 1450.00 line 5: bad record (1 fields) total 2262.00
Source
Dennis Ritchie: C Reference Manual (1975)
In this article we have read formatted input in K&R C:
scanf and its pointer arguments, the return value, failed
matches and how to get past them, literal characters, the conversions and
their pointer types, mismatched pointers on two machines, widths,
%c, assignment suppression, and sscanf for
checking input line by line. The next article covers
file I/O. Modern C covers the same functions
in scanf and
sscanf.
Author
List all K&R C tutorials.