Printing n spaces - (f) printf format

Can I print a specific number of whitespace characters?

I can not use the min. the width of the space is "\"%-5s\"" , because this will result in "str "... and I need to output "str" ...

I know I can do it stupidly:

 int len = strlen (str); printf ("/"%s/"", str); for (int i = len - 5; i > 0; i--) printf (" "); 

But I would appreciate a more efficient workaround.

+6
source share
1 answer

Try

 printf ( "%*c\"%s\"%*c", leading, ' ', str, trailing, ' '); 

Where leading and trailing are int.
For trailing use only

 printf ( "\"%s\"%*c", str, trailing, ' '); 

A similar modification can be made only for leading

EDIT
The width specifier allows you to use an asterisk to provide a variable width.
In this case,% * c tells printf to get the next argument and use it as the width for the character.
It initially reads the lead and uses it for the width of the field in which the character is printed, the space character. Then the quote \ "is printed. The format% s prints the next argument, str. Then another quote is printed, and then again% * c reads the final width for the field in which the next argument will be printed, another space character.

+9
source

Source: https://habr.com/ru/post/976603/


All Articles