将多个输入线加载到2d阵列中

时间:2016-12-01 18:13:52

标签: c multidimensional-array input

所以我必须第一次用2d数组工作,我很困惑。 我想在示例(输入)中加载多行,如该数组。

123456
654321
123456

在数组[0] [0]上应为1,数组[1] [0] - 6 .. 最重要的是线的长度是随机的,但在每一行都相同,我需要这个数字用于未来。

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

由于

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

这是一个非常快速和肮脏的解决方案。当我在处理这个时你还没有指定数据类型或最大行长度,所以这适用于任何行长度。随着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;
}