Pages

Saturday, July 30, 2016

Width Specifier

The printf width specifier sets the minimum width for an output value. Width is specified in one of two ways:
  • directly, through a decimal digit string
  • indirectly, through an asterisk (*)
If you use an "*" for the width specifier, the next argument in the call (which must be an int) specifies the minimum output field width.

Nonexistent or small field widths do NOT cause truncation of a field. If the result of a conversion is wider than the field width, the field is expanded to contain the conversion result.

WidthDescription
n At least n characters are printed. If the output less than n characters, the output is padded with blanks (right-padded if "-" flag is given, left-padded otherwise).
0n At least n characters are printed. If the output value has less than n characters, it is filled on the left with zeros.
*The argument list supplies the width specifier, which must precede the actual argument being formatted.

Examples
CodeOutput
printf("%5d",10);   10
printf("%05",10);00010
printf("%8s","Hello");   Hello
printf("%08s","Hello");   Hello (doesn't pad 0 for string)
printf("%*s",0,"Hello");Hello
printf("%*s",8,"Hello");   Hello (width given by argument)

No comments:

Post a Comment