printf right align a bracketed number

送分小仙女□ 提交于 2019-12-10 15:26:58

问题


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?


回答1:


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



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



回答3:


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

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


来源:https://stackoverflow.com/questions/12253400/printf-right-align-a-bracketed-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!