在printf的可变大小的填充 [英] Variable sized padding in printf

查看:103
本文介绍了在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屋!

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