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

I have two functions, one of which creates messages such as Starting initialization... , and the other that checks return codes and outputs of "Ok" , "Warning" or "Error" . However, the output that is created has a different length:

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

How can I get something like this:

 Starting initialization... Ok. Checking init scripts... Ok. 
+57
c string pretty-print printf
Nov 27 '09 at 15:38
source share
6 answers

You can specify the width in string fields, for example.

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

and then everything printed with this field will be filled with a space to the width you specify.

- left - aligns the text in this field.

+109
Nov 27 '09 at 15:42
source share
β€” -

printf allows formatting using width specifiers. eg.

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

You would use a negative-width specifier to indicate left justification, since the legal justification is used by default.

+15
Nov 27 '09 at 15:43
source share

There is also a %n modifier that can help in certain circumstances. It returns the column on which the row has been so far. Example: you want to write several rows that are within the width of the first row, such as 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 2 columns of the same width of any length, which can have two rows header1 and header2 . I don't know if all implementations have %n , but Solaris and Linux do.

+8
Nov 28 '09 at 19:31
source share

In addition, if you need flexibility in choosing width , you can choose one of the following two formats (with or without truncation):

 int width = 30; //no truncation printf( "%-*s %s\n", width, "Starting initialization...", "Ok." ); //truncated to the specified width printf( "%-.*s %s\n", width, "Starting initialization...", "Ok." ); 
+8
Mar 05 '15 at 4:49
source share

There's also a pretty low-tech solution for manually counting the added places so that your messages line up. Nothing prevents you from including multiple lines in message lines.

+1
Nov 27 '09 at 15:44
source share

Start by using Tabs, the \ t character modifier. It will move to a fixed location (columns, terminal jargon). However, this does not help if there are differences greater than the column width (4 characters, if I remember correctly).

To fix this, write your β€œOK / NOK” material using a fixed number of tabs (5? 6 ?, try), then return ( \ r ) without a new lining and write your message.

-2
Nov 27 '09 at 15:43
source share



All Articles