By default, printf()
seems to align strings to the right.
printf(\"%10s %20s %20s\\n\", \"col1\", \"col2\", \"col3\");
/* col1
Ill drop my 2 cents after dealing with similar issue of trying to center a table headers in a row with printf.
The following macros will need to be printed before/after the text and will align regardless of the length of the text itself. Notice that if we have odd length strings, we will not align as should(because the normal devision will result in missing space). Therefor a round up is needed, and I think this is the elegant way to solve that issue:
#define CALC_CENTER_POSITION_PREV(WIDTH, STR) (((WIDTH + ((int)strlen(STR))) % 2) \
? ((WIDTH + ((int)strlen(STR)) + 1)/2) : ((WIDTH + ((int)strlen(STR)))/2))
#define CALC_CENTER_POSITION_POST(WIDTH, STR) (((WIDTH - ((int)strlen(STR))) % 2) \
? ((WIDTH - ((int)strlen(STR)) - 1)/2) : ((WIDTH - ((int)strlen(STR)))/2))
Usage example:
printf("%*s%*s" , CALC_CENTER_POSITION_PREV(MY_COLUMN_WIDTH, "Header")
, "Header"
, CALC_CENTER_POSITION_POST(MY_COLUMN_WIDTH, "Header"), "");