tags:

views:

395

answers:

3

By default, printf() seems to align strings to the right.

printf("%10s %20s %20s\n", "col1", "col2", "col3");
/*       col1                 col2                 col3 */

I can also align text to the left like this:

printf("%-10s %-20s %-20s", "col1", "col2", "col3");

Is there a quick way to center text? Or do I have to write a function that turns a string like test into (space)(space)test(space)(space) if the text width for that column is 8?

+1  A: 

There is no printf() format specifier to centre text.

You will need to write your own function or locate a library which provides the functionality that you're looking for.

Convict
A: 

Yes, you will either have to write your own function that returns " test " etc, e.g.

printf("%s %s %s", center("col1", 10), center("col2", 20), center("col3", 20));

Or you have a center_print function, something like the following:

void center_print(const char *s, int width)
{
        int length = strlen(s);
        int i;
        for (i=0; i<=(width-length)/2; i++) {
                fputs(" ", stdout);
        }
        fputs(s, stdout);
        i += length;
        for (; i<=width; i++) {
                fputs(" ", stdout);
        }
}
hlovdal
+2  A: 

printf by itself can't do the trick, but you could play with the "indirect" width, which specifies the witdh reading it from an argument. Lets' try this (ok, not perfect)

void f(char *s)
{
        printf("---%*s%*s---\n",10+strlen(s)/2,s,10-strlen(s)/2,"");
}
int main(int argc, char **argv)
{
        f("uno");
        f("quattro");
        return 0;
}
Giuseppe Guerrini