fscanf into a 2d array in C

2019-03-04 12:54发布

I want to scan elements from a txt into an array. The txt doesn't have how many rows or columns I'm going to have, it only contains a coordinate, and the elements of the array. It looks like this:

2,3
2,1
3,0
-

How can i put these numbers into an array so that array[0][0] will be 2 and array[1][0] will be 3 etc...

I want to make this work with other inputs as well.

My code so far :

The ?? is there because I have no idea how I should declare these if I don't even know how many rows or columns every input txt will have.

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

int main()
{
FILE* in = fopen("in.txt", "r");

int x, y;

int array[??][??];

if (in == NULL) {
    printf("Can't open in.txt");
    fclose(in);
    return 1;
}

if (fscanf(in, "%d,%d\n", &x, &y) != 2) {
    printf("Cant read file.");
    return 2;
}

for (int i = 0; i < ??; i++) {
    for (int j = 0; j < ??; j++)
    fscanf(in, "%d", &array[i][j]);
}

return 0;
}

标签: c arrays scanf
2条回答
迷人小祖宗
2楼-- · 2019-03-04 13:28

You want to read in a list of value pairs? That sounds like you will need to have a (possibly long) array of sets of two numbers. Rather than remembering that X is the first and Y is the second, may I suggest setting up a structure to hold the values. Something like this should work:

int main()
{
    FILE* in = fopen("lis.csv", "r");
    int count=0;
    int error=0;
    int x, y;
    typedef struct {
        int x;
        int y;
    } COORD;
    COORD array[999]={0};
    if (in == NULL) {
        printf("Can't open in.txt");
        fclose(in);
        return 1;
    }
    while(!feof(in))
    {
        if (fscanf(in, "%d,%d\n", &x, &y) != 2) {
            printf("Cant read file.");
            error=1;
            break;
        }
        array[count].x=x;
        array[count].y=y;
        count++;
    }
    return error;
}

I did not add anything bright for the error condition and it helps if you do something with the values after reading them in but you get the idea.

查看更多
迷人小祖宗
3楼-- · 2019-03-04 13:29

You should use dynamic array allocation to scan elements from an unknown txt file into an array. for C++ programmers the best solution is std::vector. but C programmers should use alternative solutions. please read this post: (std::vector alternative for C)

查看更多
登录 后发表回答