python
python

Reputation: 308

Space padding in printf doesn't work

I need to add variable space padding before my string. Here's the code:

unsigned int spaces = result % 16;
printf("spaces=%d\n", spaces); // spaces=12, for example.
printf("% *s\n", spaces, my_string);

It simply doesn't work - spaces are not added and I'm getting following warning in gcc:

warning: ' ' flag used with ‘%s’ gnu_printf format [-Wformat=]

How to fix that? Is there any workaround for this?

Upvotes: 2

Views: 4749

Answers (1)

gsamaras
gsamaras

Reputation: 73444

Change this

printf("% *s\n", spaces, my_string);

to this

printf("%*s%s\n", spaces, " ", my_string);

This should get rid of the warning and give the desired effect.

[EDIT]

I now saw that you found already the answer. What alexis says is also correct and will produce the same effect. Alexis's version is cleaner, I would say, so I am giving this as a solution, but the credits are on him.

You could also do something like this:

int width = 5;
printf ("%*d%*d\n", width, 10, width, 12);

which will print this:

10 12

Source

So, if you think about it, you could this:

printf("%*s\n", spaces, "foo");


Why Alexis's version was synonym to your version in the comment?

Because the compiler performs concatenation of two sequential strings (i.e. with a whitespace in between) to one.

This action is called String literal concatenation. Read more in Wikipedia.

Upvotes: 4

Related Questions