【问题标题】:Load multiple input lines into 2d array将多条输入线加载到二维数组中
【发布时间】:2016-12-01 18:13:52
【问题描述】:

所以我必须第一次使用二维数组,我很困惑。 我想将示例(输入)中的多行加载到该数组中。

123456
654321
123456

在 array[0][0] 上应该是 1,array[1][0] - 6 .. 最重要的是行的长度是随机的,但每一行都是一样的,我以后需要这个数字。

最好的方法是什么?感谢您的每一个建议,请不要对我苛刻。

谢谢

【问题讨论】:

  • 尝试用代码中的赋值来解决它。打印或使用调试器查看数组的变化。
  • 你决定了一行的最大长度吗?
  • 最大长度应为 100 个标志。
  • 数据类型是int还是char
  • 必须是char

标签: c multidimensional-array input


【解决方案1】:

像这样使用 realloc

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

int main(void){
    FILE *fp = stdin;//or fopen
    char line[100+2];
    int rows = 0, cols = 0;
    fgets(line, sizeof(line), fp);
    cols = strlen(line)-1;//-1 for newline

    char (*mat)[cols] = malloc(++rows * sizeof(char[cols]));
    memcpy(mat[0], line, cols);
    while(fgets(line, sizeof(line), fp)){
        if((mat = realloc(mat, ++rows * sizeof(char[cols]))) == NULL){//In the case of a large file, realloc a plurality of times together
            perror("realloc");
            exit(EXIT_FAILURE);
        }
        memcpy(mat[rows-1], line, cols);
    }
    //fclose(fp);
    //test print
    for(int r = 0; r < rows; ++r){
        for(int c = 0; c < cols; ++c){
            printf("%c ", mat[r][c]);
        }
        puts("");
    }
    free(mat);
}

【讨论】:

  • 谢谢。但我不太了解(*mat)[cols]。我从未见过这样的代码。你能给我解释一下吗?例如,我将如何将该数组传递给函数?其他代码部分对我来说很有意义。
  • @Thomas mat 是指向char[cols] 的指针。 example of pass to function
【解决方案2】:

这是一个非常快速和肮脏的解决方案。当我处理这个时,你还没有指定数据类型或最大行长,所以这适用于任何行长。使用 2D 数组前进时要注意的重要部分是嵌套的 for() 循环。该程序的前半部分简单地确定了所需数组的大小。

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

int main(void){
    FILE* fin = fopen("fin.txt","r");
    char* line = NULL;
    size_t len = 0;
    int cols = 0, rows=1;
    int i=0, j=0;

    cols = getline(&line, &len, fin);
    cols--; // skip the newline character
    printf("Line is %d characters long\n", cols);
    while(getline(&line, &len, fin) != -1) rows++;
    printf("File is %d lines long\n", rows);
    rewind(fin);

    char array[rows][cols];
    char skip;
    for (i=0; i<rows; i++){
        for (j=0; j<cols; j++){
            fscanf(fin, "%c", &array[i][j]);
            printf("%c ", array[i][j]);
        }
        fscanf(fin, "%c", &skip); // skip the newline character
        printf("\n");
    }

    fclose(fin);
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多