printf 中的可变大小填充 [英] Variable sized padding in printf
问题描述
有没有办法在 printf
中使用可变大小的填充?
Is there a way to have a variable sized padding in printf
?
我有一个整数表示填充有多大:
I have an integer which says how large the padding is:
void foo(int paddingSize) {
printf("%...MyText", paddingSize);
}
这应该打印出 ### MyText
其中 paddingSize 应该决定 '#' 符号的数量.
This should print out ### MyText
where the paddingSize should decide the number of '#' symbols.
推荐答案
是的,如果您在格式字符串中使用 *
,它会从参数中获取一个数字:
Yes, if you use *
in your format string, it gets a number from the arguments:
printf ("%0*d
", 3, 5);
将打印005".
请记住,您只能使用空格或零填充.如果你想用其他东西填充,你可以使用类似的东西:
Keep in mind you can only pad with spaces or zeros. If you want to pad with something else, you can use something like:
#include <stdio.h>
#include <string.h>
int main (void) {
char *s = "MyText";
unsigned int sz = 9;
char *pad = "########################################";
printf ("%.*s%s
", (sz < strlen(s)) ? 0 : sz - strlen(s), pad, s);
}
sz
为 9 时输出 ###MyText
,sz
为 2 时输出 MyText
(无填充但没有截断).您可能需要检查 pad
是否太短.
This outputs ###MyText
when sz
is 9, or MyText
when sz
is 2 (no padding but no truncation). You may want to add a check for pad
being too short.
这篇关于printf 中的可变大小填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!