I l @ ve RuBoard |
Specifying fixed field widths is useful when you want to print columns of data. Because the default field width is just the width of the number, the repeated use of, say,
printf("%d %d %d\n", val1, val2, val3);would produce ragged columns if the numbers in a column had different sizes. For example, the output could look like this:
12 234 1222 4 5 23 22334 2322 10001
(This assumes that the value of the variables has been changed between print statements.)
The output can be cleaned up by using a sufficiently large fixed field width. For example, using
printf("%9d %9d %9d\n", val1, val2, val3);would yield
12 234 1222 4 5 23 22334 2322 10001
Leaving a blank between one conversion specification and the next ensures that one number never runs into the next , even if it overflows its own field. This is so because the regular characters in the control string, including spaces, are printed.
On the other hand, if a number is to be embedded in a phrase, it is often convenient to specify a field as small as or smaller than the expected number width. This makes the number fit in without unnecessary blanks. For example,
printf("Count Beppo ran %.2f miles in 3 hours.\n", distance);might produce
Count Beppo ran 10.22 miles in 3 hours.
Changing the conversion specification to %10.2f would give you this:
Count Beppo ran 10.22 miles in 3 hours.
I l @ ve RuBoard |