Alex
Alex

Reputation: 1042

printf right align a bracketed number

I'm writing a program that displays all the info in an array. It has to start with the array index in brackets (e.g. [2]) and they have to be right aligned with each other.

if it was just the number, I know that you can do:

printf("%-10d", index);

but putting brackets around that would give the following output

[         1]
[         2]
...
[        10]
[        11]

when I really want it to be:

         [1]
         [2]
...
        [10]
        [11]

How do I go about doing this?

Upvotes: 5

Views: 7175

Answers (3)

user411313
user411313

Reputation: 3990

you need only one line and no temporary char-buffer:

printf("%*s[%d]\n",12-(int)log10(index),"",index);

Upvotes: 2

Chris Desjardins
Chris Desjardins

Reputation: 2720

One easy thing to do would be to break it down to a two step process:

char tmp[128];
sprintf(tmp, "[%d]", index);
printf("%-10s", tmp);

Upvotes: 2

Do it in two steps: first build a non-aligned string in a temporary buffer, then print the string right-aligned.

char buf[sizeof(index) * (CHAR_BITS + 2) / 3 + 4];
sprintf(buf, "[%d]", index);
printf("%-12s", buf);

Upvotes: 8

Related Questions