简体   繁体   中英

Parameterizing format specifier in 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM