在printf中用星号填充?

时间:2011-08-22 03:35:55

标签: c printf

我搜索过高和低,但在C中的printf中,似乎只有零填充和空白填充。我正在寻找自己的填充,在这种情况下使用星号。

例如,

假设宽度为8个字符。

输入:123 输出:**123.00

输入:3 输出:****3.00

我该怎么做?

3 个答案:

答案 0 :(得分:7)

最简单的方法可能是使用带有空格填充的snprintf()打印到缓冲区中,然后用星号替换空格:

void print_padded(double n)
{
    char buffer[9];
    char *p;

    snprintf(buffer, sizeof buffer, "% 8.2f", n);
    for (p = buffer; *p == ' '; p++)
        *p = '*';
    printf("%s", buffer);
}

答案 1 :(得分:2)

以下程序显示了一种方法:

#include <stdio.h>
#include <stdarg.h>

void padf (size_t sz, int padch, char *fmt, ...) {
    int wid;
    va_list va;

    // Get the width that will be output.

    va_start (va, fmt);
    wid = vsnprintf (NULL, 0, fmt, va);
    va_end (va);

    // Pad if it's shorter than desired.

    while (wid++ <= sz)
        putchar (padch);

    // Then output the actual thing.

    va_start (va, fmt);
    vprintf (fmt, va);
    va_end (va);
}

int main (void) {
    padf (8, '*', "%.2f\n", 123.0);
    padf (8, '*', "%.2f\n", 3.0);
    return 0;
}

只需调用padf,就像调用printf一样,但使用额外的前导宽度和填充字符参数,并更改“实际”格式以排除前导空格或零,例如更改{{ 1}}到%8.2f

它将使用标准变量参数stuff来计算参数的实际宽度,然后输出足够的填充字符,以便在输出实际值之前将其填充到所需的宽度。根据您的要求,上述程序的输出为:

%.2f

显然,这个解决方案在左边填充 - 你可以使它更通用,并且无论你是想要左边还是右边填充(对于数字/字符串),但这可能超出了问题的范围。

答案 2 :(得分:1)

使用snprintf生成一个字符串,然后检查它的长度。对于尚未填充的任何字符,请在打印由snprintf填充的实际缓冲区之前输出星号。

例如:

#define STRINGSIZE 8

char buffer[STRINGSIZE + 1];
int length = snprintf(buffer, sizeof(buffer), "%#.2f", floating_point_value);

for (int i = STRINGSIZE - length; i > 0; i--)
{
    printf("*");
}

printf("%s\n", buffer);
相关问题