You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言打印文件生成竖线分隔表格列对齐异常如何修复?

问题根源

原来的代码仅动态计算了第三列description的最大宽度,前两列的打印宽度是硬编码的固定值(第一列7、第二列5),一旦文件中第一列的宏名、第二列的八进制值长度超过硬编码值,就会出现对齐错位。不需要手动调整,只要把前两列的最大宽度也改为动态计算即可实现任意符合格式的文件自动对齐。

修复后的完整代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

enum
{
    MAX_SIZE = 1024
};

typedef struct
{
    char define[20];
    char octal[26];
    char description[1000];
} Record;

char header1[20], header2[20], header3[20];

// 动态计算三列的最大宽度
void readFile(Record rec[], int *size, int *col1_max, int *col2_max, int *col3_max)
{
    FILE *fp = fopen("input2.txt", "r");
    if (fp == NULL)
    {
        printf("File could not be opened!");
        exit(1);
    }

    int i = 0;
    fscanf(fp, "%s %s %s\n", header1, header2, header3);
    // 初始列宽取表头长度
    *col1_max = strlen(header1);
    *col2_max = strlen(header2);
    *col3_max = strlen(header3);

    while (fscanf(fp, "%19s ", rec[i].define) == 1) 
    {
        fscanf(fp, "%10s '%[^']'", rec[i].octal, rec[i].description);
        // 动态更新各列最大宽度
        int len1 = strlen(rec[i].define);
        if (len1 > *col1_max) *col1_max = len1;
        int len2 = strlen(rec[i].octal);
        if (len2 > *col2_max) *col2_max = len2;
        int len3 = strlen(rec[i].description);
        if (len3 > *col3_max) *col3_max = len3;
        i++;
    }
    
    fclose(fp);
    *size = i;
}

void printTable(Record rec[], int size, int col1_w, int col2_w, int col3_w)
{
    // 计算分隔线总长度
    int total_len = col1_w + col2_w + col3_w + 10;
    for (int i = 0; i < total_len; i++)
        printf("-");
    printf("\n| %-*s | %*s | %-*s |\n", col1_w, header1, col2_w, header2, col3_w, header3);
    for (int i = 0; i < total_len; i++)
        printf("-");
    printf("\n");

    for (int i = 0; i < size; i++)
        printf("| %-*s | %*s | %-*s |\n", col1_w, rec[i].define, col2_w, rec[i].octal, col3_w, rec[i].description);

    for (int i = 0; i < total_len; i++)
        printf("-");
    printf("\n");
}

int main()
{
    Record recs[MAX_SIZE];
    int size = 0;
    int col1_w, col2_w, col3_w;
    readFile(recs, &size, &col1_w, &col2_w, &col3_w);
    printTable(recs, size, col1_w, col2_w, col3_w);
    return 0;
}

核心修改点

  • 读取文件时同步计算第一列(宏名)、第二列(八进制值)的最大长度,同时包含表头的长度校验,避免表头超出列宽
  • 打印表格时三列宽度都使用动态计算的数值,第一列左对齐、第二列右对齐、第三列左对齐,匹配期望输出格式
  • 分隔线总长度随三列总宽度动态计算,不会出现长度不匹配的问题
  • 如果需要适配不同输入文件,可将硬编码的文件名改为从命令行参数读取,无需重新编译代码

内容的提问来源于stack exchange,提问作者SirOdawg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 10:54:00