Pad with asterisks in 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.
For exampl开发者_StackOverflowe,
Assuming a width of 8 character.
Input: 123
Ouput: **123.00
Input: 3
Output: ****3.00
How can I do that?
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);
}
The following program shows one way of doing this:
#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;
}
Simply call padf
the same way you would call printf
but with extra leading width and padding character arguments, and changing the "real" format to preclude leading spaces or zeros, such as changing %8.2f
to %.2f
.
It will use the standard variable arguments stuff to work out the actual width of the argument then output enough padding characters to pad that to your desired width before outputting the actual value. As per your requirements, the output of the above program is:
**123.00
****3.00
Obviously, this solution pads on the left - you could make it more general and pass whether you want it left or right padded (for numerics/strings) but that's probably beyond the scope of the question.
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);
精彩评论