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
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)
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.