How can I read a file integer by integer and put them into a 2D array?

I am trying to read all the numbers from a txt file and put them into a 2D array. I shouldn’t worry about the size and stuff because I know it will be entered in 9 rows and in each row there will be 9 numbers. But if I run this code I get the following output.

int main() {
    FILE *fpointer = fopen("filename.txt", "r");
    int ch;
    int arr[9][9];
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            ch = fgetc(fpointer);
            arr[i][j] = ch;
            //printf("%d", ch);
        }
    }
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            printf("%d  ", arr[i][j]);
        }
        printf("\n");
    }
    fclose(fpointer);
    return 0;
}

Output:

49  51  52  53  54  55  48  57  50
10  52  50  49  57  56  51  55  52
49  10  51  49  50  52  57  56  55
49  51  10  52  50  51  53  49  51
53  49  49  10  50  51  52  54  51
53  55  50  49  10  53  50  51  54
55  56  50  52  53  10  54  52  54
53  56  57  51  50  49  10  53  52
57  50  57  56  51  53  54  10  50

But the entered numbers are:

134567092
421983741
312498713
423513511
234635721
523678245
646589321
549298356
234698721

I assume it maybe have to do something with the fgets() function, but I tried to use getw(), but then I get even worse numbers. Maybe it tries to read the file in hexadecimals or something. Any ideas?

>Solution :

I’m not totally sure what behavior you were hoping for here, but I recommend decoding the ASCII digits before you store the numbers in your array, like this:

arr[i][j] = ch - '0';

Also, note that fgetc will return line-ending bytes like 10, because those are characters in your file too, even if they are not exactly visible. So when you receive one of those, you need to discard it and call fgetc again. Or you could insert an extra fgetc call at the end of each line (right after your j loop) to read those.

Leave a Reply