ostream methods for controlling output format are
verbose and clumsy. Some programmers prefer the more compact ANSI C
In the previous section we showed how to read a list of and
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
printf goes to stdout and may be mixed with
printf. Here the format is specified by the first argument of the
printffunction. 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,
printfwill 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
\n is such a character. Here are some commonly
used format conversion specifications. The specification must agree
with the numeric type shown.
||Fixed format xx.xxxx. float, double|
||Scientific notation x.xxxx e nnn. float, double|
||Variable format. float, double|
||Integer xxxx. int|
|%s||Character string char *.|
cout. The string conversion can also take a width specification as in %ws.