Format output using printf


printf and its family of functions allow you to easily format string data. There are so many formatting options that it is easy to miss some of its more powerful functionality. Here is a rundown of the more useful features and some examples.

The basic printf format.

The format string is composed of a literal string that may include one or more conversion specifiers. These all begin with ‘%’ and have the format below.


# The value should be converted to an ”alternate form”. For o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively. For e, E and f, it forces the written output to contain a decimal point. For g or G the result is the same as with e or E but trailing zeros are not removed.
0 The value should be zero padded.
The converted value is to be left justified.
‘ ‘ (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.
+ A sign (+ or -) should always be placed before a number produced by a signed conversion. By default a sign is used only for negative numbers.
Thousands grouping.

minimum field width

A minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given). If the result of a conversion is wider than the field width, the field is expanded to contain the conversion result.

precision/max field width

An optional precision, in the form of a period ‘.’ followed by a number which represents the maximum number of significant digits, or the maximum number of characters to be printed from a string.


hh char
h short
l long
ll long long
L long double
j intmax_t, uintmax_t
z size_t, ssize_t
t ptrdiff_t

conversion specifier

d,i The int argument is converted to signed decimal notation.
u An unsigned int.
o,x,X An unsigned octal (o), or unsigned hexadecimal (x and X) notation.
e,E The double [-]d.ddde┬▒dd where there is one digit before the decimal-point character and the number of digits after it is equal to the precision. if the precision is missing, it is taken as 6; if the precision is zero, no decimal-point character appears. An E conversion uses the letter E (rather than e) to introduce the exponent.
f,F The double argument is rounded and converted to decimal notation in the style [-]ddd.ddd.
c An unsigned char.
s A pointer to an array of character type (pointer to a string). The array must contain a terminating null.
p The void * pointer argument is printed in hexadecimal (as if by %#x or %#lx).
% A ‘%’ is written. No argument is converted. The complete conversion specification is ‘%%’.


The entire family of printf functions including fprintf, sprintf, snprintf, vprintf, vfprintf, vsprintf, and vsnprintf take advantage of these formatting rules as well. In addition, many other languages have printf implementations which operate in much the same way.