Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. 
like image 278
psihodelia Avatar asked Nov 27 '09 15:11

psihodelia


People also ask

What format is used to print a string with the printf function?

C++ printf is a formatting function that is used to print a string to stdout. The basic idea to call printf in C++ is to provide a string of characters that need to be printed as it is in the program. The printf in C++ also contains a format specifier that is replaced by the actual value during execution.

How do you do %s in printf?

%s tells printf that the corresponding argument is to be treated as a string (in C terms, a 0-terminated sequence of char ); the type of the corresponding argument must be char * . %d tells printf that the corresponding argument is to be treated as an integer value; the type of the corresponding argument must be int .

What is %s in printf?

%s and string We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.


1 Answers

You can specify a 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.

like image 82
Carl Smotricz Avatar answered Sep 21 '22 03:09

Carl Smotricz