How to format strings using printf() to get equal length in the output?

psihodelia picture psihodelia · Nov 27, 2009 · Viewed 143.6k times · Source

I have two functions, one which produces messages like Starting initialization... and another which checks return codes and outputs "Ok", "Warning" or "Error". However, the output that is produced is of the different length:

Starting initialization...Ok.
Checking init scripts...Ok.

How can I get something like this:

Starting initialization...       Ok.
Checking init scripts...         Ok.

Answer

Carl Smotricz picture Carl Smotricz · Nov 27, 2009

You can specify width on string fields, e.g.

printf("%-20s", "initialization...");

and then whatever's printed with that field will be blank-padded to the width you indicate.

The - left-justifies your text in that field.