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;
}
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:
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.
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)