Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pad with asterisks in printf?

Tags:

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.

For example,

Assuming a width of 8 character.

Input: 123 Ouput: **123.00

Input: 3 Output: ****3.00

How can I do that?

like image 570
Ben C. Avatar asked Aug 22 '11 03:08

Ben C.


2 Answers

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);
}
like image 151
caf Avatar answered Sep 24 '22 18:09

caf


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.

like image 45
paxdiablo Avatar answered Sep 26 '22 18:09

paxdiablo