Alex Rivera | Logout

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

Asked 2009-11-27T15:38:54.880
134

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 the following?

Starting initialization...       Ok.
Checking init scripts...         Ok.
Edit
Report

3 Answers

30

printf allows formatting with width specifiers. For example,

printf( "%-30s %s\n", "Starting initialization...", "Ok." );

You would use a negative width specifier to indicate left-justification because the default is to use right-justification.

answered 2009-11-27T15:43:42.807
17

There's also the %n modifier which can help in certain circumstances. It returns the column on which the string was so far. Example: you want to write several rows that are within the width of the first row like a table.

int width1, width2;
int values[6][2];
printf("|%s%n|%s%n|\n", header1, &width1, header2, &width2);

for(i=0; i<6; i++)
   printf("|%*d|%*d|\n", width1, values[i][0], width2, values[i][1]);

will print two columns of the same width of whatever length the two strings header1 and header2 may have. I don't know if all implementations have the %n, but Solaris and Linux do.

answered 2009-11-28T19:31:13.133
1

There's also the rather low-tech solution of counting adding spaces by hand to make your messages line up. Nothing prevents you from including a few trailing spaces in your message strings.

answered 2009-11-27T15:44:15.457

Your Answer