5

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?

3 Answers 3

8

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); 
Sign up to request clarification or add additional context in comments.

Comments

2

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); 

Comments

2

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

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

2 Comments

It wasn't stated as a requirement, but this only works if index > 0.
Yeah, premature optimization and over-engineering all the way down, making your code impossible to debug or maintain 6 months from now. ;-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.