Formatted output in K&R C
last modified December 5, 2026 K&R C 1978
C has no input or output statements. Reading and writing is done by
functions of the standard I/O library, and the most used of them is
printf. It converts numbers, characters, and strings to text
under the control of a format string. The earlier articles have
used it with %d, %s, and %c; this
article covers the conversions, field widths, and precisions in full, and
the related functions sprintf and fprintf.
Conversions
The first argument of printf is the format string. Ordinary
characters in it are copied to the output. Each % starts a
conversion specification, which takes the next argument and
prints it in the form the conversion character names.
#include <stdio.h>
int main()
{
int n;
n = 200;
printf("decimal %d, octal %o, hex %x\n", n, n, n);
printf("character %c has the code %d\n", 'K', 'K');
printf("string: %s\n", "Hello there!");
printf("a percent sign: 100%%\n");
return 0;
}
%d prints an integer in decimal, %o in octal, and
%x in hexadecimal. %c prints an integer as a
character, so the same constant 'K' appears once as a letter
and once as its code. %s prints a string, and
%% prints a percent sign without taking an argument. The
arguments must match the conversions in number and in type.
$ gcc -std=c89 -pedantic -Wall -Wextra -o conv conv.c $ ./conv decimal 200, octal 310, hex c8 character K has the code 75 string: Hello there! a percent sign: 100%
Unsigned and long values
%u prints an integer as unsigned. A long argument
needs the letter l before the conversion character:
%ld, %lo, and %lx.
#include <stdio.h>
int main()
{
unsigned u;
long big;
u = 0;
u = u - 1;
printf("%u as unsigned, %d as int\n", u, u);
printf("in octal %o, in hex %x\n", u, u);
big = 100000L * 25;
printf("%ld\n", big);
printf("%lo %lx\n", big, big);
return 0;
}
Subtracting 1 from an unsigned zero gives the largest unsigned
value, a word with every bit set. %u shows it as a positive
number and %d as -1; the octal and hexadecimal forms show the
bits. With a 32-bit int the value is 4294967295.
$ gcc -std=c89 -pedantic -Wall -Wextra -o unsig unsig.c $ ./unsig 4294967295 as unsigned, -1 as int in octal 37777777777, in hex ffffffff 2500000 11422640 2625a0
On the PDP-11 an unsigned has 16 bits, and the same program
prints 65535 and six octal digits. The long results are the
same, because a long has 32 bits on the PDP-11, and its
l conversions read all of them.
$ cc unsig.c $ a.out 65535 as unsigned, -1 as int in octal 177777, in hex ffff 2500000 11422640 2625a0
Field width
A number between the % and the conversion character is the
field width: the minimum number of characters to print. A shorter
value is padded on the left with blanks. A minus sign before the width
adjusts the value to the left, and a width that starts with a zero pads a
number with zeros.
#include <stdio.h>
int main()
{
printf("|%d|%6d|%-6d|%06d|\n", 42, 42, 42, 42);
printf("|%d|%6d|%-6d|%06d|\n", -7, -7, -7, -7);
printf("|%3d|\n", 12345);
printf("|%s|%10s|%-10s|\n", "pdp", "pdp", "pdp");
printf("|%c|%4c|%-4c|\n", 'x', 'x', 'x');
return 0;
}
The vertical bars show the edges of each field. A value that is wider than
its field is not cut; %3d prints all five digits of 12345.
The zero padding goes after the minus sign of a negative number. The width
works the same way for strings and characters.
$ gcc -std=c89 -pedantic -Wall -Wextra -o width width.c $ ./width |42| 42|42 |000042| |-7| -7|-7 |-00007| |12345| |pdp| pdp|pdp | |x| x|x |
Floating-point conversions
%f prints a floating-point number in decimal notation,
%e in scientific notation, and %g chooses the
shorter of the two and drops trailing zeros. A float argument
is converted to double in the call, so the same conversions
serve both types. A period and a number after the width set the
precision: the number of digits after the decimal point for
%f and %e, and of significant digits for
%g. The default is six.
#include <stdio.h>
int main()
{
double x;
x = 2.0 / 3.0;
printf("%f %e %g\n", x, x, x);
printf("%.2f %.2e %.2g\n", x, x, x);
printf("|%10.3f|%-10.3f|\n", x, x);
x = 1000000.0 / 7.0;
printf("%f %e %g\n", x, x, x);
printf("%g %g %g\n", 0.0001, 100000.0, 1000000.0);
return 0;
}
%10.3f prints three decimals in a field of ten characters.
%g switches to scientific notation when the exponent is less
than -4 or not less than the precision, so 100000 is still printed in full
and a million is 1e+06.
$ gcc -std=c89 -pedantic -Wall -Wextra -o floats floats.c $ ./floats 0.666667 6.666667e-01 0.666667 0.67 6.67e-01 0.67 | 0.667|0.667 | 142857.142857 1.428571e+05 142857 0.0001 100000 1e+06
The V7 printf writes %g in its own way. It omits
the zero before the decimal point, and it chooses scientific notation
already for 100000, writing it with the decimal point and no zeros:
1.e+05.
$ cc floats.c $ a.out 0.666667 6.666667e-01 .666667 0.67 6.67e-01 .67 | 0.667|0.667 | 142857.142857 1.428571e+05 142857 .0001 1.e+05 1.e+06
Precision of strings
For a string, the precision is the maximum number of characters to print. Combined with the width and the minus sign, it cuts strings into columns of a fixed size.
#include <stdio.h>
int main()
{
char *s;
s = "Hello there!";
printf(":%s:\n", s);
printf(":%15s:\n", s);
printf(":%-15s:\n", s);
printf(":%.5s:\n", s);
printf(":%15.5s:\n", s);
printf(":%-15.5s:\n", s);
printf(":%5s:\n", s);
return 0;
}
The colons mark the edges of the fields. %.5s prints the first
five characters, and %15.5s prints them in a field of fifteen
characters. A width smaller than the string, as in %5s, prints
the whole string.
$ gcc -std=c89 -pedantic -Wall -Wextra -o strprec strprec.c $ ./strprec :Hello there!: : Hello there!: :Hello there! : :Hello: : Hello: :Hello : :Hello there!:
Rounding
A precision smaller than the number of digits rounds the printed value. Two things decide the result: the binary value the machine has stored, which is usually not the decimal number of the source, and the rule for a value that lies exactly halfway.
#include <stdio.h>
int main()
{
double third;
printf("%.0f %.0f %.0f %.0f\n", 0.5, 1.5, 2.5, 3.5);
printf("%.2f %.2f %.2f\n", 0.125, 1.005, 2.675);
third = 1.0 / 3.0;
printf("%.17f\n", third);
return 0;
}
0.5, 1.5, 2.5, 3.5, and 0.125 are exact binary fractions, so they are real ties, and the GNU C library rounds ties to the even digit: 0, 2, 2, 4, and 0.12. 1.005 and 2.675 are stored as values slightly below the decimal ones, so they are rounded down. Seventeen digits show the error of the stored value of one third.
$ gcc -std=c89 -pedantic -Wall -Wextra -o rounding rounding.c $ ./rounding 0 2 2 4 0.12 1.00 2.67 0.33333333333333331
The PDP-11 gives other results. Its printf rounds a tie
upward, so 2.5 becomes 3 and 0.125 becomes 0.13. Its double
has a 56-bit fraction against the 53 bits of the IEEE format: it stores
1.005 as a value slightly above 1.005, which rounds to 1.01, and its third
is closer to the true value, printed with a 4 at the end.
$ cc rounding.c $ a.out 1 2 3 4 0.13 1.01 2.67 0.33333333333333334
Unchecked arguments
printf takes a variable number of arguments of any types, and
nothing in the language connects them to the format string. The function
learns from the conversions what to fetch, and if the arguments are
different, it fetches the wrong thing.
#include <stdio.h>
int main()
{
long big;
double x;
big = 100000L;
x = 3.5;
printf("%d %d\n", big, 7);
printf("%d\n", x);
printf("%f\n", 7);
printf("%d %d\n", 1);
return 0;
}
The program passes a long to %d, a
double to %d, an int to
%f, and one argument for two conversions. GCC knows the
format rules of printf and checks literal format strings with
-Wformat, which is part of -Wall; a compiler of
the time had no such check. On x86-64 the first arguments travel in
registers, integers and floating-point numbers in different ones. The
long happens to print correctly, because %d
reads the low half of its register, and the other conversions print
whatever their registers held.
$ gcc -std=c89 -pedantic -Wall -Wextra -o badargs badargs.c
badargs.c: In function ‘main’:
badargs.c:10:14: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long int’ [-Wformat=]
10 | printf("%d %d\n", big, 7);
| ~^ ~~~
| | |
| int long int
| %ld
badargs.c:11:14: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat=]
11 | printf("%d\n", x);
| ~^ ~
| | |
| int double
| %f
badargs.c:12:14: warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘int’ [-Wformat=]
12 | printf("%f\n", 7);
| ~^ ~
| | |
| | int
| double
| %d
badargs.c:13:17: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=]
13 | printf("%d %d\n", 1);
| ~^
| |
| int
$ ./badargs
100000 7
1048658592
3.500000
1 0
On the PDP-11 the arguments lie on the stack one after another, and
printf steps through them by the sizes the conversions name. The
long 100000 takes two words; %d prints the first
one, 1, and the second %d the other half, -31072, so the 7 is
never printed. The second line shows the first word of 3.5.
%f takes four words, the 7 and three words after it, which
make a tiny number. The missing argument of the last line is the word that the previous call left on the
stack.
$ cc badargs.c $ a.out 1 -31072 16736 0.000000 1 16736
A formatted table
Widths and precisions together line up the columns of a report. The next program prints an invoice from an array of structures.
#include <stdio.h>
#define NITEMS 4
struct item {
char *it_name;
int it_qty;
double it_price;
} items[NITEMS] = {
{ "tape reel", 12, 18.5 },
{ "disk pack", 2, 295.0 },
{ "line printer ribbon", 30, 4.25 },
{ "terminal", 1, 1450.0 }
};
int main()
{
int i;
double amount, total;
printf("%-20s %5s %9s %10s\n", "item", "qty", "price", "amount");
total = 0;
for (i = 0; i < NITEMS; i++) {
amount = items[i].it_qty * items[i].it_price;
printf("%-20s %5d %9.2f %10.2f\n", items[i].it_name,
items[i].it_qty, items[i].it_price, amount);
total += amount;
}
printf("%-36s %10.2f\n", "total", total);
return 0;
}
The heading uses the same widths as the rows, with %s for the
column names. Strings are adjusted to the left and numbers to the right, so
the decimal points line up. The total is printed in a field as wide as the
first three columns together, 20 + 1 + 5 + 1 + 9 = 36 characters, so that
its amount falls under the amount column.
$ gcc -std=c89 -pedantic -Wall -Wextra -o invoice invoice.c $ ./invoice item qty price amount tape reel 12 18.50 222.00 disk pack 2 295.00 590.00 line printer ribbon 30 4.25 127.50 terminal 1 1450.00 1450.00 total 2389.50
Formatting into a string
sprintf works like printf, but stores the result
in a character array, given as the first argument, instead of printing it.
The result is an ordinary string ending with a null character.
#include <stdio.h>
#include <string.h>
int main()
{
char label[40];
int i;
for (i = 1; i <= 3; i++) {
sprintf(label, "tape-%03d.dat", i * 7);
printf("%s has %d characters\n", label, (int) strlen(label));
}
sprintf(label, "%d + %d = %d", 20, 22, 20 + 22);
printf("[%s]\n", label);
return 0;
}
The first loop builds file names with numbers padded to three digits. The
array must be large enough for the result and its null character;
sprintf does not know its size and writes past the end of an
array that is too small. The strings article
covers strlen.
$ gcc -std=c89 -pedantic -Wall -Wextra -o label label.c $ ./label tape-007.dat has 12 characters tape-014.dat has 12 characters tape-021.dat has 12 characters [20 + 22 = 42]
Error messages
A program has two output streams: the standard output, for its results, and
the standard error, stderr, for messages about its work.
fprintf takes the stream as its first argument and then works
like printf.
#include <stdio.h>
int main()
{
int i, n;
n = 0;
for (i = 1; i <= 5; i++) {
if (i == 3) {
fprintf(stderr, "skipping item %d\n", i);
continue;
}
printf("item %d\n", i);
n++;
}
fprintf(stderr, "%d items written\n", n);
return 0;
}
When the standard output is redirected to a file or a pipe, the messages
still reach the terminal, and the output is not mixed with them. The shell
redirects the standard error with 2> and the standard
output with >; /dev/null discards what is
written to it. The file I/O article
covers streams in full.
$ gcc -std=c89 -pedantic -Wall -Wextra -o errout errout.c $ ./errout 2>/dev/null item 1 item 2 item 4 item 5 $ ./errout >/dev/null skipping item 3 4 items written
Source
Dennis Ritchie: C Reference Manual (1975)
Linux manual: printf, fprintf, sprintf
In this article we have printed values with printf in
K&R C: the conversion characters, long and unsigned
values, field widths, precisions for numbers and strings, rounding on two
machines, arguments that do not match the format, a table,
sprintf, and messages on stderr. The next
article, formatted input, reads values
with scanf. Modern C covers the same functions in
printf and
sprintf.
Author
List all K&R C tutorials.