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?
By using justifications in printf statement we can arrange the data in any format. To implement the right justification, insert a minus sign before the width value in the %s character.
You can use the :> , :< or :^ option in the f-format to left align, right align or center align the text that you want to format. We can use the fortmat() string function in python to output the desired text in the order we want.
Note: If you want to right justify the string, use ljust(). You can also use format() for formatting of the strings.
Alignment of Strings Using the format() Method in Python To left-align a string, we use the “:<n” symbol inside the placeholder. Here n is the total length of the required output string. Left Aligned String with length 10 is: Scaler . To right align a string, we use the “:>n” symbol inside the placeholder.
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);
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);
you need only one line and no temporary char-buffer:
printf("%*s[%d]\n",12-(int)log10(index),"",index);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With