c - 如何在 C 中格式化表格

标签 c arrays unix formatting

我是 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/

相关文章:

linux - 报告守护进程状态的 UNIX/Linux 惯用方式

c - 如何 fread() 结构?

c - 如何在c中打印内存位

JavaScript 复制对象数组

c++ - 在 C++ 中用十六进制值初始化一个无符号字符数组

c - 我怎样才能找出哪个图书馆是给定对象的所在地?

linux - XAMPP:另一个 Web 服务器守护进程已经在运行?

c - 根据用户输入和 C 中的模式填充矩阵

c - 为什么会出错?我想用 C 语言编写移动平均代码

java - 列表中的调用长度和列表的特定项目