在printf中参数化格式说明符 [英] Parameterizing format specifier in printf

查看:244
本文介绍了在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");

正如你所看到的,如果我想改变它们之间的间距,我将不得不改变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 \n", width, "Identity");

其中 width 类型为 int 保存字段宽度值。您可以更改宽度的值以更改字段宽度。

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.

及相关的,

and related,


如上所述,字段宽度或精度或者两者都可以用星号表示。在
这种情况​​下,一个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆