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?
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
int
argument supplies the field width or precision.[...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With