printf() formatting

The formatting string

The first argument to printf() is a character string that specifies the format for any following arguments. The character string can include normal text, as well as a conversion specification for each further argument. An example of this might be:

printf( "hex number in wide field---> %#12x <---\n", 0x64 );

The conversion specifications consist of these elements, which are described below:

Optional elements go between the % and the conversion character. Multiple optional elements must be given in the order listed above.

Conversion specifiers

basic
item
argument type(s)effect
%d, %i int signed decimal display
%o octal display
%x hexadecimal display using lowercase a-f
%X hexadecimal display using uppercase A-F
%u unsigned unsigned decimal display
%c char
%s char * The pointer is presumed to point to a null-terminated text string.
%f float signed number with decimals
%e signed number with decimals and a power of 10 marked by 'e'
%E signed number with decimals and a power of 10 marked by 'E'
%g signed number, possibly with decimals and/or a power of 10 marked by 'e'.
%G signed number, possibly with decimals and/or a power of 10 marked by 'E'.
%p a pointer to
any object
(may need to be cast to void *)
%n int * This conversion is special — it does not produce any output at all. However, the pointer argument must point to an integer variable, which will be filled with the count of characters written to this point. The count can then be used in subsequent calculations.
%% none This writes a literal "%" character in the output stream.

Conversion flags

FlagFormat
-left adjustment
+always print a numeric sign
spaceuse a blank space for positive numbers (default)
0pad with leading zeros
#alternate output form

Conversion width and precision

Width or precision or both may be specified as *, in which case the value is computed by converting the next argument(s), which must be int.

Conversion length modifier

characterFormat
hshort or unsigned short
llong or unsigned long
Llong double

Based on "The C Programming Language" by Kernighan and Ritchie, and various web resources such as this C Language Reference Manual (may be a dead link).