printf format specifiers
A cheat sheet for printf in C, from %d, %f, %s and %c to width, precision and %zu for sizes.
printf replaces each % code in the format string with the next argument. The code must match the argument's type:
| Specifier | Type | Example output |
|---|---|---|
%d |
int |
42 |
%f, %.2f |
double |
3.141593, 3.14 |
%c |
char |
A |
%s |
string (char *) |
hello |
%zu |
size_t (from sizeof, strlen) |
8 |
%x |
unsigned, in hex |
ff |
%% |
a literal percent sign | % |
A number between % and the letter sets a minimum width: %5d pads to 5 characters, and %-5d pads on the right. Mismatched types are undefined behavior, so compile with -Wall, which checks format strings for you.
Example
#include <stdio.h>
int main(void) {
printf("[%5d] [%-5d] [%.2f]\n", 42, 42, 3.14159);
printf("%s scored %d%%\n", "Ada", 95);
return 0;
}
Output:
[ 42] [42 ] [3.14]
Ada scored 95%