next up previous
Next: Handling new datatypes with Up: The ostream, istream, ofstream Previous: ostream methods

Formatting with ANSI C printf

The ostream methods for controlling output format are verbose and clumsy. Some programmers prefer the more compact ANSI C approach.

In the previous section we showed how to read a list of $x$ and $y$ values and create a table in a well-defined format. Here is how to do the same thing with the ANSI C printf function call. Output from printf goes to stdout and may be mixed with cout.

#include <stdio.h>

   // Write a column header
   printf("\n  x     y\n");
   for( i = 0; i < 10; i++)

Notice that we need the ANSI C header stdio.h with printf. Here the format is specified by the first argument of the printf function. The percent signs % in the format string introduce the format conversion specification. There are two of them, one for each value written. They are taken in order reading from left to right. Each output value should have a corresponding format specification. The 7.4 specifies a field width of 7 and 4 digits past the decimal point. The f specifies "fixed" format (i.e. not scientific notation with powers of 10). Omitting the field width is OK, but then you can't line up the numbers. The field width is actually treated as a minimum request. If the value requires more space than you allow, printf will grab more space. Of course, the numbers won't line up, then, but that is much preferable to a misleading truncation.

Other than format conversion specifications, any characters in the format string are copied into the output as given. In this example the end-of-line \n is such a character. Here are some commonly used format conversion specifications. The specification must agree with the numeric type shown.

printf field purpose
%w.df Fixed format xx.xxxx. float, double Scientific notation x.xxxx e nnn. float, double
%w.dg Variable format. float, double
%wd Integer xxxx. int
%s Character string char *.
The g format produces either f, e or d type output depending on the magnitude of the number and whether there are only zeros after the decimal point. This is just like the default behavior of cout. The string conversion can also take a width specification as in %ws.

next up previous
Next: Handling new datatypes with Up: The ostream, istream, ofstream Previous: ostream methods
Carleton DeTar 2008-11-10