Printf right aligns the number in parentheses

I am writing a program that displays all the information in an array. It should start with the array index in brackets (for example, [2]), and they should be aligned to the right with each other.

if it was just a number, I know what you can do:

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

but placing brackets around this will give the following output

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

when I really want it to be:

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

How should I do it?

+5
source share
3 answers

Do this in two steps: first create a line that is not aligned in the temporary buffer, then print the line in a straight line alignment.

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

One simple task is to break it down into a two-step process:

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

char -buffer:

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

All Articles