Sorry I am very new to C and I'm having a hard time. I have an input text file that reads:
5 3
383 386 287
415 293 335
368 492 149
421 362 27
190 59 263
and I am trying to read this into a 2D array. What I am trying is this:
FILE * fin = NULL;
fin = fopen("myTestData.txt", "r");
int twod[MAX_ROWS][MAX_COLS];
int i, j, num, row, col;
fscanf(fin, "%d%d", &row, &col);
fclose(fin);
fin = fopen("myTestData.txt", "r");
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
fscanf(fin, "%i ", &num);
twod[i][j] = num;
}
}
The problem I am having is that on the first row where the blank is (twod[0][2]) it is assigning it the value of the first integer of the second row (383). What can I do so that [0][2] gets a null value?
Thanks for any help
Remove the lines where you close and reopen the file. After you read in the number of rows and columns, you simply need to process the remaining data, which will be well structured - as are most homework problems.
FILE * fin = NULL;
fin = fopen("myTestData.txt", "r");
int twod[MAX_ROWS][MAX_COLS];
int i, j, num, row, col;
fscanf(fin, "%d%d", &row, &col);
//fclose(fin);
//fin = fopen("myTestData.txt", "r");
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
fscanf(fin, "%i ", &num);
twod[i][j] = num;
}
}
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
printf("%d ", twod[i][j]);
printf("\n");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With