fscanf into a 2d array in C

前端 未结 2 881
旧巷少年郎
旧巷少年郎 2021-01-28 10:12

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

相关标签:
2条回答
  • 2021-01-28 10:32

    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)

    0 讨论(0)
  • 2021-01-28 10:53

    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.

    0 讨论(0)
提交回复
热议问题