Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading a text file of non-even lines into 2D array

Tags:

arrays

c

2d

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

like image 596
Lost_in_C_space Avatar asked Nov 01 '22 11:11

Lost_in_C_space


1 Answers

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");
}
like image 68
AbdullahC Avatar answered Nov 15 '22 06:11

AbdullahC