printf is probably the first function every C programmer uses. Most people only know %d and %s, but the format string can do much more: set column widths, line up numbers, pad with zeros, show signs, limit decimals and cut long strings. This lesson is a practical guide to format specifiers, ending with a neat receipt and safe string building with snprintf.
In this lesson you will learn
- The parts of a format specifier: flags, width, precision, length, type
- Conversions for integers, floating point, characters and strings
- Aligning output in columns, and widths passed with
* - Length modifiers such as
%ld,%lldand%zu - Building strings safely with
snprintf
You should know basic input and output and data types.
The Shape of a Specifier
Every specifier starts with % and ends with a type letter. Optional parts can come in between, in this order:
% [flags] [width] [.precision] [length] type
% - 8 .2 f → "3.14 "
% 0 5 ll d → "00042"
Conversions, Widths and Flags
#include <stdio.h>
int main(void) {
int n = 42, neg = -7;
unsigned int u = 3000000000u;
double pi = 3.14159265;
char grade = 'A';
const char *city = "Chattogram";
/* Basic conversions */
printf("%%d %d and %d\n", n, neg);
printf("%%u %u\n", u);
printf("%%f %f %%.2f %.2f %%e %e\n", pi, pi, pi);
printf("%%c %c %%s %s\n", grade, city);
printf("%%x %x %%X %X %%o %o %%#x %#x\n", 255, 255, 8, 255);
/* Width and alignment */
printf("[%8d] [%-8d] [%08d]\n", n, n, n);
printf("[%12s] [%-12s] [%.3s]\n", city, city, city);
printf("[%+d] [%+d] [% d]\n", n, neg, n);
printf("[%8.3f] [%-8.1f]\n", pi, pi);
/* Width from an argument with * */
for (int w = 4; w <= 8; w += 2)
printf("[%*d]\n", w, n);
/* Printing a percent sign, and the return value */
int written = printf("Discount: 15%%\n");
printf("printf returned %d (characters written)\n", written);
return 0;
}
Output
%d 42 and -7
%u 3000000000
%f 3.141593 %.2f 3.14 %e 3.141593e+00
%c A %s Chattogram
%x ff %X FF %o 10 %#x 0xff
[ 42] [42 ] [00000042]
[ Chattogram] [Chattogram ] [Cha]
[+42] [-7] [ 42]
[ 3.142] [3.1 ]
[ 42]
[ 42]
[ 42]
Discount: 15%
printf returned 14 (characters written)
%dprints signed integers and%uunsigned ones.%x,%Xand%oprint hexadecimal and octal; the#flag adds the0xprefix.%fshows 6 decimals by default;%.2frounds to 2.%euses scientific notation.- A number before the type is the minimum width. Values are right-aligned by default; the
-flag left-aligns them, and the0flag pads numbers with zeros. - For strings, precision is a maximum length:
%.3sprints only “Cha”. +always shows the sign, and a space puts a blank where a plus sign would go, so positive and negative numbers line up.%*dtakes the width from an extra argument, which is useful when the width is only known at run time.%%prints a single percent sign.printfreturns the number of characters it wrote.
A Real Use: Printing a Receipt
#include <stdio.h>
struct Item { const char *name; int qty; double price; };
int main(void) {
struct Item cart[] = {
{"Rice (5 kg)", 2, 410.0},
{"Lentils", 3, 135.5},
{"Soybean oil (1 L)", 1, 189.75},
{"Tea", 4, 62.0},
};
int n = sizeof cart / sizeof cart[0];
double total = 0;
printf("%-20s %4s %9s %10s\n", "Item", "Qty", "Price", "Amount");
printf("%.*s\n", 46, "----------------------------------------------");
for (int i = 0; i < n; i++) {
double amount = cart[i].qty * cart[i].price;
total += amount;
printf("%-20s %4d %9.2f %10.2f\n", cart[i].name, cart[i].qty, cart[i].price, amount);
}
printf("%-20s %25.2f\n", "Total", total);
/* snprintf builds a string safely, never writing past the buffer */
char label[16];
int needed = snprintf(label, sizeof label, "Invoice #%05d-%s", 42, "DHAKA");
printf("label = \"%s\" (needed %d chars, buffer holds %zu)\n", label, needed, sizeof label - 1);
/* Long values need the right length modifier */
long long views = 9876543210LL;
size_t bytes = sizeof cart;
printf("views %lld, cart uses %zu bytes\n", views, bytes);
return 0;
}
Output
Item Qty Price Amount
----------------------------------------------
Rice (5 kg) 2 410.00 820.00
Lentils 3 135.50 406.50
Soybean oil (1 L) 1 189.75 189.75
Tea 4 62.00 248.00
Total 1664.25
label = "Invoice #00042-" (needed 20 chars, buffer holds 15)
views 9876543210, cart uses 96 bytes
- Text columns use
%-20s(left-aligned) and number columns use%9.2f(right-aligned), so the decimal points line up. - The total uses a width of 25, which is the width of the other three columns plus the spaces between them, so it lands under the Amount column.
%.*stakes the precision from an argument: here it prints exactly 46 dashes from a longer string.snprintfwrites into a buffer but never more than its size, and always adds the closing'\0'. Its return value is how many characters the full text needed (20), so you can tell it was cut short.- Use the right length modifier:
%lldforlong longand%zuforsize_t.
The compiler noticed that the label would not fit and printed a warning, which is why this example’s file name ends in _warn. Paying attention to such warnings is a good habit.
Quick Reference
| Type | Specifier | Type | Specifier |
|---|---|---|---|
int | %d or %i | unsigned int | %u, %x, %o |
long | %ld | long long | %lld |
size_t | %zu | pointer difference (ptrdiff_t) | %td |
double (and float) | %f, %e, %g | long double | %Lf |
char | %c | string | %s |
| pointer | %p (cast to void *) | int32_t etc. | PRId32 macros |
Common Mistakes
- A specifier that does not match the type, such as
%dwith adouble. This is undefined behaviour; compile with-Wallso the compiler warns you. - Passing user text as the format:
printf(name). If the name contains%, it is read as a specifier. Writeprintf("%s", name). - Using
sprintfinstead ofsnprintf, which can write past the end of the buffer. - Using
%lfinprintfand thinking it differs from%f. Inprintfboth print adouble. Inscanf, though,%lfis required fordouble.
Practice Exercises
Exercise 1. What do printf("[%6.1f]", 2.35) and printf("[%-5d|%05d]", 42, 42) print?
Show answer
[ 2.4]: width 6 with one decimal. The stored value of 2.35 is really 2.35000000000000008882…, a tiny bit above 2.35, so it rounds up. (A number stored just below a halfway point would round down, so be careful with such values.) The second prints [42 |00042].
Exercise 2. Print a time such as 7 hours, 5 minutes, 9 seconds as 07:05:09.
Show answer
int h = 7, m = 5, s = 9;
printf("%02d:%02d:%02d\n", h, m, s); /* 07:05:09 */
Frequently Asked Questions
Why does printf accept %f for both float and double?
Arguments to functions with a variable number of parameters go through “default promotions”: a float is turned into a double, and char and short into int. So printf only ever receives a double.
What does %g do?
%g uses normal notation for ordinary sizes and switches to scientific notation for very large or very small numbers. It also removes trailing zeros. It is handy for printing numbers whose size you do not know in advance.
Summary
- A specifier is
%[flags][width][.precision][length]type. - Width sets a minimum size;
-left-aligns;0pads with zeros. - Precision sets decimals for numbers and maximum length for strings.
- Match the type exactly, and build strings with
snprintf.
Next: C memcpy, memmove and memset.
