问题
I have a few lines of output like the following:
printf("%-20s %-20s %-20s %-20s %-20s \n", "Identity", "Identity", "float", "double", "long double");
printf("%-20s %-20s %-20s %-20s %-20s \n", "Number", "LHS", "error", "error", "error");
As you can see, if I wanted to change the spacing between them, I would have to change the number 20 ten times. Is there a way to parameterize the format specifier? So that changing only once would change them all?
回答1:
Yes, you can make the field width an asterisk (*), and supply the value as an int argument. Something like
printf("%-*s \n", width, "Identity");
where width is of type int holding the field width value. You can change the value of width to change the field width.
To quote the C11 standard regarding this, chapter §7.21.6.1, fprintf(),
An optional minimum field width. [...] The field width takes the form of an asterisk
*(described later) or a nonnegative decimal integer.
and related,
As noted above, a field width, or precision, or both, may be indicated by an asterisk. In this case, an
intargument supplies the field width or precision.[...]
来源:https://stackoverflow.com/questions/35462452/parameterizing-format-specifier-in-printf