Thursday 15 July 2010

c - Space padding in printf doesn't work -



c - Space padding in printf doesn't work -

i need add together variable space padding before string. here's code:

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

it doesn't work - spaces not added , i'm getting next warning in gcc:

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

how prepare that? there workaround this?

change this

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

to this

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

this should rid of warning , give desired effect.

[edit]

i saw found answer. alexis says right , produce same effect. alexis's version cleaner, say, giving solution, credits on him.

you this:

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

which print this:

10 12

source

so, if think it, this:

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

why alexis's version synonym version in comment?

because compiler performs concatenation of 2 sequential strings (i.e. whitespace in between) one.

this action called string literal concatenation. read more in wikipedia.

c printf

No comments:

Post a Comment