如何使用 printf 将表格数据左对齐?
How to align tabular data to the left with 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 个浮点数。在每一行,我想显示它们对齐。这段代码就是这样做的。但是,数据是右对齐的。我们可以在下图中看到结果:
我怎样才能做这样的事情,但将数据左对齐?
在格式字符串中使用标志“-”,如
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] );
}
来自C标准(7.21.6.1 fprintf函数)
6 The flag characters and their meanings are:
'-' The result of the conversion is left-justified within the field. (It is right-justified if this flag is not specified.)
假设我们想要在 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 个浮点数。在每一行,我想显示它们对齐。这段代码就是这样做的。但是,数据是右对齐的。我们可以在下图中看到结果:
我怎样才能做这样的事情,但将数据左对齐?
在格式字符串中使用标志“-”,如
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] );
}
来自C标准(7.21.6.1 fprintf函数)
6 The flag characters and their meanings are:
'-' The result of the conversion is left-justified within the field. (It is right-justified if this flag is not specified.)