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

如何在C语言中从标准输入读取矩阵并存入二维数组?

如何将剩余输入存入二维数组board[height][width]?

首先得提一句,你之前用strlen判断第一行长度的方式其实不太靠谱——比如如果第一行是带多个空格的6 4,strlen会大于4,但这其实是完全合法的输入。更稳妥的方式是直接用sscanf解析第一行的两个整数,同时通过返回值判断是否成功读取了两个有效值。

接下来处理剩余输入的核心思路很简单:不管剩余数字和第一行在同一行还是分多行输入,我们只需要按顺序读取足够数量的整数(正好是width * height个),然后按行优先的规则填入二维数组就行。

下面是完整的实现代码,我会一步步拆解关键部分:

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

int main() {
    char buf[100]; // 定义足够大的缓冲区,避免输入溢出
    if (fgets(buf, sizeof(buf), stdin) == NULL) {
        printf("Cannot decode\n");
        return 1;
    }

    // 解析宽度和高度,同时验证第一行是否是两个合法整数
    int width, height;
    if (sscanf(buf, "%d %d", &width, &height) != 2) {
        printf("Cannot decode\n");
        return 1;
    }

    // 检查宽高是否合法,避免0或负数导致数组越界
    if (width <= 0 || height <= 0) {
        printf("Cannot decode\n");
        return 1;
    }

    int total_elements = width * height;
    // 用变长数组存储(C99及以上编译器支持,老编译器可以看后面的动态分配方案)
    int board[height][width];
    int count = 0;

    // 循环读取所有需要的元素
    while (count < total_elements) {
        int num;
        // scanf会自动跳过空格、换行等空白字符,不管输入格式如何都能正确读取
        if (scanf("%d", &num) != 1) {
            printf("Cannot decode\n");
            return 1;
        }

        // 可选:验证输入的数字是0或1(符合你的示例输入要求)
        if (num != 0 && num != 1) {
            printf("Cannot decode\n");
            return 1;
        }

        // 计算当前元素的行和列:行优先填充
        int row = count / width;
        int col = count % width;
        board[row][col] = num;
        count++;
    }

    // 可选:打印数组验证是否正确存入
    printf("验证数组内容:\n");
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            printf("%d ", board[i][j]);
        }
        printf("\n");
    }

    return 0;
}

关键细节说明:

  • 替换strlen判断:用sscanf的返回值判断是否成功读取两个整数,比单纯判断字符串长度可靠得多,能兼容带任意空格的合法输入。
  • 行优先填充逻辑:count从0开始递增,count / width得到当前元素所在的行号,count % width得到列号,正好把输入的数字按顺序填入每一行的每一列,和你给出的6宽4高、24个数字的示例完全匹配。
  • 兼容性处理:如果你的编译器不支持变长数组(比如老的C89编译器),可以用动态分配的方式创建二维数组:
    // 动态分配二维数组
    int **board = malloc(height * sizeof(int*));
    if (board == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    for (int i = 0; i < height; i++) {
        board[i] = malloc(width * sizeof(int));
        if (board[i] == NULL) {
            // 分配失败时要释放已分配的内存,避免内存泄漏
            for (int j = 0; j < i; j++) free(board[j]);
            free(board);
            printf("Memory allocation failed\n");
            return 1;
        }
    }
    
    // 使用完记得释放内存
    // for (int i = 0; i < height; i++) free(board[i]);
    // free(board);
    
  • 鲁棒性错误处理:每一步都做了合法性检查,包括输入读取失败、宽高非法、数字不是0/1的情况,确保程序不会因为异常输入崩溃。

内容的提问来源于stack exchange,提问作者승기유

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:40:51