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

C语言从文本文件读取参数创建矩阵:读取数字遇阻求助

从文本文件读取参数创建矩阵的问题

我现在需要完成一个任务:从文本文件读取参数,并用这些参数创建矩阵,但卡在了读取数字的环节,已经折腾好几个小时了。文本文件的格式是每行包含三个数字和一个字母(L或S),文件里有多行这种格式的内容。

我目前写的代码片段如下:

#include <stdio.h>
#include <stdlib.h>
typedef struct matrix {//create a struct of matrix
    int** mat;//the name
    int rows, cols, start;//How ma...

解决方案思路

首先,咱们得先解决每行参数的读取问题——这明显是你当前的卡点。文本每行的格式是三个整数 + 一个字符(L/S),这里推荐用fgets配合sscanf来读取,比直接用fscanf更稳妥,能避免不少格式匹配的坑。

步骤1:完善结构体定义

先把你的matrix结构体补全,加上存储L/S的字段,方便后续创建矩阵时区分逻辑:

typedef struct matrix {
    int** mat;          // 矩阵指针
    int rows, cols;     // 矩阵的行、列数
    int start;          // 起始值(根据你的注释推测)
    char type;          // 存储每行的L/S标识
} Matrix;

步骤2:读取文本文件的每行内容

假设你的文本文件名为params.txt,每行格式比如是3 5 1 L,可以用以下方式逐行读取并解析:

int main() {
    FILE* fp = fopen("params.txt", "r");
    if (fp == NULL) {
        perror("Failed to open file");
        exit(EXIT_FAILURE);
    }

    char line[100];  // 存储每行内容,长度可根据实际需求调整
    Matrix* matrices = NULL;
    int count = 0;   // 记录读取到的参数行数(即要创建的矩阵数量)

    // 逐行读取文件
    while (fgets(line, sizeof(line), fp) != NULL) {
        int rows, cols, start;
        char type;
        // 解析每行的四个参数:三个整数 + 一个字符
        if (sscanf(line, "%d %d %d %c", &rows, &cols, &start, &type) == 4) {
            // 动态扩容矩阵数组
            matrices = realloc(matrices, (count + 1) * sizeof(Matrix));
            if (matrices == NULL) {
                perror("Failed to allocate memory");
                exit(EXIT_FAILURE);
            }
            // 给当前矩阵的参数赋值
            matrices[count].rows = rows;
            matrices[count].cols = cols;
            matrices[count].start = start;
            matrices[count].type = type;
            count++;
        } else {
            printf("Warning: Invalid line format, skipping\n");
        }
    }
    fclose(fp);

    // 接下来根据每个matrix的参数创建对应的矩阵
    for (int i = 0; i < count; i++) {
        // 分配行指针
        matrices[i].mat = malloc(matrices[i].rows * sizeof(int*));
        if (matrices[i].mat == NULL) {
            perror("Failed to allocate row pointers");
            exit(EXIT_FAILURE);
        }
        // 分配每行的列内存,并根据type填充值(这里示例L为左到右递增,S为右到左递增)
        for (int j = 0; j < matrices[i].rows; j++) {
            matrices[i].mat[j] = malloc(matrices[i].cols * sizeof(int));
            if (matrices[i].mat[j] == NULL) {
                perror("Failed to allocate column memory");
                exit(EXIT_FAILURE);
            }
            int base_val = matrices[i].start + j * matrices[i].cols;
            for (int k = 0; k < matrices[i].cols; k++) {
                if (matrices[i].type == 'L') {
                    matrices[i].mat[j][k] = base_val + k;
                } else if (matrices[i].type == 'S') {
                    matrices[i].mat[j][k] = base_val + (matrices[i].cols - 1 - k);
                }
            }
        }
    }

    // 测试输出所有矩阵
    for (int i = 0; i < count; i++) {
        printf("Matrix %d (Type: %c, %dx%d, Start: %d):\n", i+1, matrices[i].type, matrices[i].rows, matrices[i].cols, matrices[i].start);
        for (int j = 0; j < matrices[i].rows; j++) {
            for (int k = 0; k < matrices[i].cols; k++) {
                printf("%d ", matrices[i].mat[j][k]);
            }
            printf("\n");
        }
        printf("\n");
    }

    // 最后释放所有动态分配的内存,避免泄漏
    for (int i = 0; i < count; i++) {
        for (int j = 0; j < matrices[i].rows; j++) {
            free(matrices[i].mat[j]);
        }
        free(matrices[i].mat);
    }
    free(matrices);

    return 0;
}

关键注意点

  • 容错性处理:用fgets读取整行再解析,能跳过格式错误的行,避免程序直接崩溃。
  • 内存管理:动态分配的内存一定要逐层释放,尤其是矩阵的行指针和列内存,防止内存泄漏。
  • 参数合法性校验:可以在解析后加判断,比如rows和cols不能为0或负数,确保创建矩阵的参数有效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:01:33