Parameterizing format specifier in printf

柔情痞子 提交于 2019-12-04 03:58:30

问题


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 int argument supplies the field width or precision.[...]



来源:https://stackoverflow.com/questions/35462452/parameterizing-format-specifier-in-printf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!