Centering strings with printf()

Posted by Pieter on Stack Overflow See other posts from Stack Overflow or by Pieter
Published on 2010-03-17T11:06:24Z Indexed on 2010/03/17 11:31 UTC
Read the original article Hit count: 309

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about printf

Related posts about c