我有几行输出,如下所示:
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");
Run Code Online (Sandbox Code Playgroud)
如你所见,如果我想改变它们之间的间距,我将不得不将数字改为20次.有没有办法参数化格式说明符?那么只改变一次会改变它们吗?
是的,您可以将字段宽度*
设为星号(),并将值作为int
参数提供.就像是
printf("%-*s \n", width, "Identity");
Run Code Online (Sandbox Code Playgroud)
其中包含字段宽度值width
的类型int
.您可以更改值width
以更改字段宽度.
引用C11
有关此标准,第7.21.6.1章fprintf()
,
可选的最小 字段宽度.[...]字段宽度采用星号
*
(稍后描述)或非负十进制整数的形式.
和相关的,
如上所述,字段宽度或精度或两者可以用星号表示.在这种情况下,
int
参数提供字段宽度或精度.[...]