如何使用printf将表格数据左对齐?
假设我们想要在 C 语言中使用 printf 显示以表格方式对齐的不同值。
我们可以这样做:
#include <stdio.h>
int main()
{
char strings[5][10] = {"Test1","Test2","Test3","Test4","Test5"};
int ints[5] = {1,2,3,4,5};
float floats[5] = {1.5,2.5,3.5,4.5,5.5};
int i;
printf("%10s%10s%10s\n","Strings","Ints","Floats");
for(i=0;i<5;i++){
printf("%10s%10d%10.2f\n",strings[i],ints[i],floats[i]);
}
return 0;
}
在这个例子中,我们有 5 个字符串、5 个整数和 5 个浮点数。在每一行,我想将它们对齐显示。这段代码就是这样做的。但是,数据是右对齐的。我们可以在下图中看到结果:
我怎样才能做这样的事情,但将数据向左对齐?
Let us suppose that we want to display different values aligned in a tabular way, in C, using printf.
We can do something like this:
#include <stdio.h>
int main()
{
char strings[5][10] = {"Test1","Test2","Test3","Test4","Test5"};
int ints[5] = {1,2,3,4,5};
float floats[5] = {1.5,2.5,3.5,4.5,5.5};
int i;
printf("%10s%10s%10s\n","Strings","Ints","Floats");
for(i=0;i<5;i++){
printf("%10s%10d%10.2f\n",strings[i],ints[i],floats[i]);
}
return 0;
}
In this example, we have 5 strings, 5 ints, and 5 floats. At each line, I would like to display them aligned. This piece of code does this. However, the data is aligned to the right. We can see the result in the following image:
How can I do something like this, but aligning the data to the left?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在格式字符串中使用标志“-”,如
来自 C 标准 (7.21.6.1 fprintf 函数)
Use the flag '-' in the format strings like
From the C Standard (7.21.6.1 The fprintf function)