Load multiple input lines into 2d array

2019-09-19 15:14发布

问题:

So I have to work for the first time with 2d array and I am confused. I want to load multiple lines like are in example (input), to that array.

123456
654321
123456

On array[0][0] should be 1, array[1][0] - 6 .. The most important thing is that length of line is random but in every line same and I need that number for the future.

What is the best way to do it? Thanks for every advice and please dont be harsh on me.

Thanks

回答1:

Use realloc like this

#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);
}


回答2:

Here is a very quick and dirty solution. When I was working on this you hadn't yet specified data type or max line length, so this works for any line length. The important part to note as you move forward with 2D arrays is the nested for() loops. The first half of this program simply determines the size of the array needed.

#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;
}