This item was added on: 2003/03/22

Formatting output with `printf`

is surprisingly simple once you get used to it. The first argument to `printf`

is a format string which determines the number and type of values. The types of values are determined by single letter, the types are:

d /* int, signed base 10 */
i /* int, signed base 10 */
o /* int, unsigned base 8, no leading 0 */
x /* int, unsigned base 16, abcdef with no leading 0x */
X /* int, unsigned base 16, ABCDEF with no leading 0X */
u /* int, unsigned base 10 */
s /* char *, nul terminated sequence of characters */
c /* int, single character */
f /* double, notation [-]mm.dd */
e /* double, notation [-]m.dde[+/-]xx */
E /* double, notation [-]m.ddE[+/-]xx */
g /* double, %e if exponent is less than -4 or >= the precision, %f otherwise */
G /* double, %E if exponent is less than -4 or >= the precision, %f otherwise */
p /* void *, implementation dependent representation */
n /* int *, the number of characters written so far. Assigned to the argument */
% /* print a % character */

A format flag begins with the % character, after which maybe one of the following prior to the conversion character:
1: Flags that modify the specification:
-, specifies left adjustment
+, specifies that the number will be printed with a sign space, space prefix if no sign is present
0, pads numbers with leading zeros
#, alternate output form.
%o, prefix with 0
%x, prefix with 0x
%X, prefix with 0X
%e, E, f, g, G, always show a radix point
%g, %G, show trailing zeros
2: A number specifying the minimum field width.
3: A period, separating field width from precision
4: A number specifying the precision length
5: A length modifier, h, l, or L. h specifies a short or unsigned short value,
l specifies a long or unsigned long, and L specifies long double.

The width or precision can be replaced with *, where the value is computed

from the next integer argument. Here are some uses of these formats:
#include <stdio.h>
int main ( void )
{
printf ( "%5d\n", 123 );
printf ( "%*d\n", 5, 123 );
printf ( "%+05d\n", 123 );
printf ( "%x\n", 123U );
printf ( "%#x\n", 123U );
printf ( "%#X\n", 123U );
printf ( "%-10.2f\n", 12.3 );
printf ( "%10.2f\n", 12.3 );
printf ( "%lu\n", 123UL );
printf ( "%s\n", "Testing" );
printf ( "%c\n", 'A' );
return 0;
}

Credit: Prelude