fgets in a loop repeats data in the 2d array

Viewed 78

I am trying to get my 9x9 grid of numbers from a file and store it in a 2D int array. For this, I wrote my code so that it uses fgets() from the file and then converts the char array values to an int and then stores it in that respective spot in the array.

While I thought it was working, when I printed out the array, I noticed how it has repeated values (from the previous row that it read) and it doesn't print out the full 9x9 grid. Here is what I mean:

 int strIndex = 1; // Goes every odd to extract number

   /* Need to do this for the whole grid */
    for(int i = 0; i < 9; i++) {
        fgets(str,19, f);
        strIndex = 1;
        // printf("%s\n", str);
        for(int j = 0; j < 9; j++) {
            // Since asci digits start at 48, subtracting gets you the num
            grid[i][j] = (int) str[strIndex] - 48; 
            strIndex = strIndex + 2;
        }
    }

This is what I am supposed to be getting (basically whatever is in input.txt):

 8 2 7 1 5 4 3 9 6 
 9 6 5 3 2 7 1 4 8 
 3 4 1 6 8 9 7 5 2 
 5 9 3 4 6 8 2 7 1 
 4 7 2 5 1 3 6 8 9 
 6 1 8 9 7 2 4 3 5 
 7 8 6 2 3 5 9 1 4 
 1 5 4 7 9 6 8 2 3 
 2 3 9 8 4 1 5 6 7 

But this is what I am getting:

8 2 7 1 5 4 3 9 6 

-38 2 7 1 5 4 3 9 6 

9 6 5 3 2 7 1 4 8 

-38 6 5 3 2 7 1 4 8 

3 4 1 6 8 9 7 5 2 

-38 4 1 6 8 9 7 5 2 

5 9 3 4 6 8 2 7 1 

-38 9 3 4 6 8 2 7 1 

4 7 2 5 1 3 6 8 9 

Am I using fgets() correctly? And what is -38? I can't seem to understand why that is being printed instead of the actual number. (For ex: Instead of 8 from grid[0][0], it prints -38 in grid[0][1]. In fgets, I made the space 19 because I noticed how fgets() also takes in whitespace, so that's why my strIndex is incrementing every 2.

Thanks

1 Answers
fgets(str,19, f)

That doesn't read the whole line. Your lines have 19 visible characters but there is a newline (\n) character at the end of each line. By reading only 19 characters you leave the newline for the next fgets. Hence every second fgets call will read a single newline character with the rest of the buffer retained from the previous line. The newline ascii value is 10 and that is where the -38 comes from since the code does str[strIndex] - 48.

So the fix would be to read 20 characters rather than 19. In fact, it wouldn't hurt to put an even larger buffer. Say 32 bytes. fgets will stop at the newline anyway.

Related