C conversion specifiers and modifiers
By Flavio
Tagged: C
A handy reference to the C conversion specifiers used with printf() and scanf(), like %d, %u, %s, and %f, plus the modifiers that set the field width.
In this post I want to create a helpful reference for the C conversion specifiers you can use, commonly with printf(), scanf() and similar I/O functions. See also basic I/O and C variables and types.
| Specifier | Meaning |
|---|---|
%d / %i | Signed decimal integer |
%u | Unsigned decimal integer |
%c | Unsigned char |
%s | String |
%p | Pointer in hexadecimal form |
%o | Unsigned octal integer |
%x / %X | Unsigned hexadecimal number |
%e | Floating point number in exponential format in e notation |
%E | Floating point number in exponential format in E notation |
%f | double number in decimal format |
%g / %G | double number in decimal format or exponential format depending on the value |
%% | Literal % |
%a / %A | Hexadecimal floating point (C99) |
%b / %B | Binary integer output (C23). printf("%b", 5) prints 101. Needs a recent libc (glibc since 2.35). macOS and MSVC support may vary. |
%n | Writes the number of characters printed so far into an int* argument |
In addition to those specifiers, we have a set of modifiers.
Let’s start with digits. Using a digit between % and the format specifier, you can tell the minimum field width. Example: %3d will take 3 spaces regardless of the number printed.
This:
printf("%4d\n", 1);
printf("%4d\n", 12);
printf("%4d\n", 123);
printf("%4d\n", 1234);
should print
1
12
123
1234
If you put a dot before the digit, you are now telling the precision: the number of decimal digits. This of course applies to decimal numbers. Example:
printf("%4.2f\n", 1.0);
printf("%4.3e\n", 12.232432442);
printf("%4.1e\n", 12.232432442);
printf("%4.1f\n", 123.22);
will print:
1.00
1.223e+01
1.2e+01
123.2
In addition to digits, we have length modifiers. The common ones are h, l and L, plus a few from C99:
h, used with integer numbers, indicates ashort int(for example%hd) or ashort unsigned int(for example%hu)hh(C99), achar, for example%hhdl, used with integer numbers, indicates along int(for example%ld) or a long unsigned int (for example%lu).ll(C99), along long, for example%lldL, used with floating point numbers, indicates along double, for example%Lfz(C99), asize_t, for example%zuforsizeofj(C99), anintmax_tt(C99), aptrdiff_t
Want me to talk about your product? You can sponsor this site.