C语言 printf 中的可变大小填充
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4133318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Variable sized padding in printf
提问by Egil
Is there a way to have a variable sized padding in printf?
有没有办法在 中有一个可变大小的填充printf?
I have an integer which says how large the padding is:
我有一个整数表示填充有多大:
void foo(int paddingSize) {
printf("%...MyText", paddingSize);
}
This should print out ### MyTextwhere the paddingSize should decide the number of '#' symbols.
这应该打印出### MyTextpaddingSize 应该决定“#”符号数量的位置。
回答by paxdiablo
Yes, if you use *in your format string, it gets a number from the arguments:
是的,如果您*在格式字符串中使用,它会从参数中获取一个数字:
printf ("%0*d\n", 3, 5);
will print "005".
将打印“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);
}
This outputs ###MyTextwhen szis 9, or MyTextwhen szis 2 (no padding but no truncation). You may want to add a check for padbeing too short.
这输出###MyTextwhensz是 9,或者MyTextwhensz是 2(没有填充但没有截断)。您可能想要添加一个检查pad太短。
回答by cflute
Be careful though - some compilers at least (and this may be a general C thing) will not always do what you want:
不过要小心——至少有些编译器(这可能是一个通用的 C 语言)并不总是你想要的:
char *s = "four";
printf("%*.s\n", 5, s); // Note the "."
This prints 5 spaces;
这将打印 5 个空格;
char *s = "four";
printf("%*s\n", 3, s); // Note no "."
This prints all four characters "four"
这将打印所有四个字符“四”
回答by Quixotic
You could write like this :
你可以这样写:
void foo(int paddingSize) {
printf ("%*s",paddingSize,"MyText");
}
回答by Valerii Stankov
better use std::cout
更好地使用 std::cout
using namespace std;
cout << setw(9) //set output width
<< setfill('#') // set fill character
<< setiosflags(ios_base::right) //put padding to the left
<< "MyText";
should produce:
应该产生:
###MyText
回答by Graeme Perrow
printf( "%.*s", paddingSize, string );
For example:
例如:
const char *string = "12345678901234567890";
printf( "5:%.*s\n", 5, string );
printf( "8:%.*s\n", 8, string );
printf( "25:%.*s\n", 25, string );
displays:
显示:
5:12345
8:12345678
25:12345678901234567890

