Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering strings with printf()

Tags:

c

printf

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?

like image 872
Pieter Avatar asked Mar 17 '10 11:03

Pieter


People also ask

How to center text in printf java?

To center the string for output we use the StringUtils. center() method from the Apache Commons Lang library. This method will center-align the string str in a larger string of size using the default space character (' ').

How to center text in c?

You can use the gotoxy() function, like in C++, but in C, it is not pre defined so you should define it first. Another way is to just tab and newline (\t and \n...)

How to make output in center in c?

There's no direct way to center text. You'll have to combine several elements: Figure out how many digits you have. Calculate how many spaces you want before and after the number.


2 Answers

printf by itself can't do the trick, but you could play with the "indirect" width, which specifies the width by 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; } 
like image 196
Giuseppe Guerrini Avatar answered Sep 19 '22 09:09

Giuseppe Guerrini


@GiuseppeGuerrini's was helpful, by suggesting how to use print format specifiers and dividing the whitespace. Unfortunately, it can truncate text.

The following solves the problem of truncation (assuming the field specified is actually large enough to hold the text).

void centerText(char *text, int fieldWidth) {     int padlen = (fieldWidth - strlen(text)) / 2;     printf("%*s%s%*s\n", padLen, "", text, padlen, ""); }  
like image 43
clearlight Avatar answered Sep 23 '22 09:09

clearlight