notnull
notnull

Reputation: 2028

Print n space characters -(f)printf format

Is there any way to print certain amount of whitespace characters?

I cant use min. width whitespace padding "\"%-5s\"", because it would result to "str "..., and I need to output "str" ...

I know I can do it a dumb way:

int len = strlen (str);

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

But I'd appreciate more effective workaround.

Upvotes: 7

Views: 5968

Answers (1)

user3121023
user3121023

Reputation: 8286

Try

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

Where leading and trailing are int.
For trailing only use

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

Similar modification can be made for leading only

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

Upvotes: 12

Related Questions