本文介绍了printf的右对齐一个括号数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在写一个显示阵列中的所有信息的程序。它开始用括号中的数组索引(如 [2]
),他们必须是正确的互相对齐。
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]
当我真的希望它是:
[1]
[2]
...
[10]
[11]
我如何去这样做?
How do I go about doing this?
推荐答案
做它在两个步骤:先建立一个临时缓冲区不结盟字符串,然后打印字符串右对齐
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);
这篇关于printf的右对齐一个括号数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!