在 printf 中参数化格式说明符 [英] Parameterizing format specifier in printf
问题描述
我有几行输出如下:
printf("%-20s %-20s %-20s %-20s %-20s
", "Identity", "Identity", "float", "double", "long double");
printf("%-20s %-20s %-20s %-20s %-20s
", "Number", "LHS", "error", "error", "error");
如您所见,如果我想更改它们之间的间距,我必须将数字 20 更改十次.有没有办法参数化格式说明符?所以只改变一次就会改变它们?
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?
推荐答案
是的,您可以将字段宽度设为星号 (*
),并将值提供为int
参数.类似的东西
Yes, you can make the field width an asterisk (*
), and supply the value as an int
argument. Something like
printf("%-*s
", width, "Identity");
其中 width
是 int
类型,保存字段宽度值.您可以更改 width
的值来更改字段宽度.
where width
is of type int
holding the field width value. You can change the value of width
to change the field width.
引用 C11
标准,第 7.21.6.1 章,fprintf()
,
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.
和相关的,
如上所述,字段宽度或精度或两者都可以用星号表示.在在这种情况下,int
参数提供字段宽度或精度.[...]
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.[...]
这篇关于在 printf 中参数化格式说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!