next up previous
Next: Reading and Writing to Up: Formatting output Previous: Formatting under ostream

Formatting with ANSI C printf

Here is how to do the same thing with the ANSI C printf statement. Output from printf goes to stdout and may be mixed with cout.

#include <stdio.h>

   // Write a column header
   printf("\n  x     y\n");
   printf("--------------\n");
   for( i = 0; i < 10; i++)
     printf("%7.4f%7.4f\n",x[i],y[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
%w.de 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: Reading and Writing to Up: Formatting output Previous: Formatting under ostream
Carleton DeTar 2007-10-31