我是 C 的新手,仍在尝试弄清楚一些格式化的东西。我想知道如何打印一个数组给它特定数量的列并将数组元素向右或向左对齐。
因此,如果我使用整数数组(一维),如何以包含行和列的表格格式打印该数组?
最佳答案
您阅读了 printf formatting和功能引用。以此代码为例,按您的方式工作。
#include <stdio.h>
int main(void)
{
enum alignment { RIGHT, LEFT};
int tableAlignment = RIGHT;
int i;
int columnWidth = 5; // Set max column Width of Table
int cellWidth = 11; // Set Max Cell Width
char cellFormat[10];
int data[10] = { 1, 20, 300, 4000, 50000, 600000, 7000000, 80000000, 900000000, 1000000000};
// Set Cell Alignment
// Set cellWidth
// Set data type according to the data
if ( tableAlignment == RIGHT )
{
sprintf(cellFormat,"%%%s%d%s","",cellWidth,"d");
}
else if ( tableAlignment == LEFT )
{
// - for Left-justification
sprintf(cellFormat,"%%%s%d%s","-",cellWidth,"d");
}
else
{
fprintf(stderr, "Error: Invalid Alignment");
}
printf("%s\n",cellFormat);
for ( i = 1; i <= 10; ++i )
{
printf(cellFormat, data[i-1]);
// break line reaching max columnWidth
if ( ((i) % columnWidth ) == 0 ) printf("\n");
}
printf("\n");
return 0;
}
关于c - 如何在 C 中格式化表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28376951/