Pad with asterisks in printf?

后端 未结 3 1671
再見小時候
再見小時候 2021-01-19 03:19

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 asteris

3条回答
  •  余生分开走
    2021-01-19 03:43

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

提交回复
热议问题