Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf right align a bracketed number

Tags:

c

format

printf

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?

like image 542
Alex Avatar asked Sep 03 '12 20:09

Alex


People also ask

How do I align printf to the right?

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.

How do I print a right align in Python?

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.

How do you right justify text in Python?

Note: If you want to right justify the string, use ljust(). You can also use format() for formatting of the strings.

How do you align a string in Python?

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.


3 Answers

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);
like image 130
Gilles 'SO- stop being evil' Avatar answered Sep 30 '22 08:09

Gilles 'SO- stop being evil'


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);
like image 28
Chris Desjardins Avatar answered Sep 30 '22 08:09

Chris Desjardins


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

printf("%*s[%d]\n",12-(int)log10(index),"",index);
like image 22
user411313 Avatar answered Sep 30 '22 08:09

user411313