Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterizing format specifier in printf

Tags:

c

format

printf

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?

like image 729
QuestionEverything Avatar asked Feb 08 '23 17:02

QuestionEverything


1 Answers

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.[...]

like image 128
Sourav Ghosh Avatar answered Feb 16 '23 04:02

Sourav Ghosh