在 printf 中用星号填充? [英] Pad with asterisks in printf?

查看:52
本文介绍了在 printf 中用星号填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've searched high and low, but in printf in C it seems that there's only zero fill and white space fill. I'm looking to write my own fill, in this case using the asterisk.

例如

假设宽度为 8 个字符.

Assuming a width of 8 character.

输入:123输出:**123.00

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

我该怎么做?

推荐答案

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

The simplest way is probably to print into a buffer using snprintf() with space padding, then replace the spaces with asterisks afterwards:

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);
}

这篇关于在 printf 中用星号填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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