Next: Output Conversion Syntax, Up: Formatted Output

#### 12.12.1 Formatted Output Basics

The `printf` function can be used to print any number of arguments. The template string argument you supply in a call provides information not only about the number of additional arguments, but also about their types and what style should be used for printing them.

Ordinary characters in the template string are simply written to the output stream as-is, while conversion specifications introduced by a ‘`%`’ character in the template cause subsequent arguments to be formatted and written to the output stream. For example,

         int pct = 37;
         char filename[] = "foo.txt";
         printf ("Processing of `%s' is %d%% finished.\nPlease be patient.\n",
         	filename, pct);

produces output like

         Processing of `foo.txt' is 37% finished.
         Please be patient.

This example shows the use of the ‘`%d`’ conversion to specify that an `int` argument should be printed in decimal notation, the ‘`%s`’ conversion to specify printing of a string argument, and the ‘`%%`’ conversion to print a literal ‘`%`’ character.

There are also conversions for printing an integer argument as an unsigned value in octal, decimal, or hexadecimal radix (‘`%o`’, ‘`%u`’, or ‘`%x`’, respectively); or as a character value (‘`%c`’).

Floating-point numbers can be printed in normal, fixed-point notation using the ‘`%f`’ conversion or in exponential notation using the ‘`%e`’ conversion. The ‘`%g`’ conversion uses either ‘`%e`’ or ‘`%f`’ format, depending on what is more appropriate for the magnitude of the particular number.

You can control formatting more precisely by writing modifiers between the ‘`%`’ and the character that indicates which conversion to apply. These slightly alter the ordinary behavior of the conversion. For example, most conversion specifications permit you to specify a minimum field width and a flag indicating whether you want the result left- or right-justified within the field.

The specific flags and modifiers that are permitted and their interpretation vary depending on the particular conversion. They're all described in more detail in the following sections. Don't worry if this all seems excessively complicated at first; you can almost always get reasonable free-format output without using any of the modifiers at all. The modifiers are mostly used to make the output look “prettier” in tables.