Pad with asterisks in printf?

后端 未结 3 1666
再見小時候
再見小時候 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:52

    Generate a string using snprintf, and then check it's length. For any characters that haven't been filled, output an asterik before printing the actual buffer that was filled by snprintf.

    So for instance:

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

提交回复
热议问题