Sams Teach Yourself C in 21 Days

(singke) #1
The precision specifier consists of a decimal point (.) by itself or followed by a number.
A precision specifier applies only to the conversion characters e,E,f,g,G, ands. It spec-
ifies the number of digits to display to the right of the decimal point or, when used with
s, the number of characters to output. If the decimal point is used alone, it specifies a
precision of 0.
The field-width specifier determines the minimum number of characters output. The
field-width specifier can be the following:


  • A decimal integer not starting with 0. The output is padded on the left with spaces
    to fill the designated field width.

  • A decimal integer starting with 0. The output is padded on the left with zeros to fill
    the designated field width.
    •Thecharacter. The value of the next argument (which must be an int) is used as
    the field width. For example, if wis a type intwith a value of 10 , the statement
    printf(“%
    d”, w, a);prints the value of awith a field width of 10.
    If no field width is specified, or if the specified field width is narrower than the output,
    the output field is just as wide as needed.
    The last optional part of the printf()format string is the flag, which immediately fol-
    lows the %character. There are four available flags:

  • This means that the output is left-justified in its field rather
    than right-justified, which is the default.



  • This means that signed numbers are always displayed with a
    leading+or-.
    ‘ ‘ A space means that positive numbers are preceded by a space.

    This applies only to x,X, andoconversion characters. It speci-


    fies that nonzero numbers are displayed with a leading 0Xor
    0x(forxandX) or a leading 0 (foro).




When you use printf(), the format string can be a string literal enclosed in double
quotes in the printf()argument list. It can also be a null-terminated string stored in
memory, in which case you pass a pointer to the string to printf(). For example, this
statement
char *fmt = “The answer is %f.”;
printf(fmt, x);
is equivalent to this statement
printf(“The answer is %f.”, x);

364 Day 14

22 448201x-CH14 8/13/02 11:12 AM Page 364

Free download pdf