在printf的可变大小的填充 [英] Variable sized padding in printf
问题描述
有没有办法让在的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\n", 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\n", (sz < strlen(s)) ? 0 : sz - strlen(s), pad, s);
}
此输出 ### MYTEXT
在 SZ
为9,或 MYTEXT
在 SZ
2(无填充,但没有截断)。您可能希望增加对垫
太短检查。
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屋!