Pad with asterisks in printf?

I searched high and low, but in printf in C it seems that only zero padding and space are filled. I want to write my own fill, in this case using an asterisk.

For instance,

Assuming a width of 8 characters.

Input: 123 Output: **123.00

Input: 3 Output: ****3.00

How can i do this?

+4
source share
3 answers

The easiest way is probably to print to the buffer using snprintf() with a space, and then replace the spaces with asterisks:

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

The following program shows one way:

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

Just call padf just like you would call printf , but with extra leading width and padding characters, and change the "real" format to exclude leading spaces or zeros, for example, change %8.2f to %.2f .

It will use standard argument arguments to work out the actual width of the argument, and then print enough indentation to fill to the desired width before returning the actual value. According to your requirements, the output of the above program:

 **123.00 ****3.00 

Obviously, this solution is located on the left - you can make it more general and convey whether you want it to stay left or right (for numbers / lines), but this is probably beyond the scope of the question.

+2
source

Generate the string using snprintf , and then check the length. For any characters that were not filled, print asterik before printing the actual buffer that was filled by snprintf .

So for example:

 #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); 
+1
source

All Articles