Search code examples
cmatrix

Problem reading a matrix in a .txt file with fscanf


I have a problem with reading a txt file in my C code, the format of my txt file is :

10

5

1

1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50

With 10 being my number of columns (describe as dim.x in my code), 5 the number of rows (dim.y) and 1 the number of "2" in my matrix (which is not really important here).

my code to read this .txt file is

//CoupleInt contain just 2 int, x and y   
    CoupleInt dim;
    int nbrCible;
    FILE* fichier = fopen("sample.txt", "r");
    int items_lus = fscanf(fichier, "%d %d %d", &dim.x, &dim.y, &nbrCible);
//pre condtions in between ...
    int map[dim.x][dim.y];
    int compteurCible = 0;

    for(int y=0; y<dim.y; y++){
        for(int x=0; x<dim.x; x++){
            if(fscanf(fichier, "%d ", &map[y][x])!=1){
                printf("Stop");
                return 1;
            };
            if (map[y][x] == 2){
                compteurCible++;
            }
        }
    }

    for(int y=0; y<dim.y; y++){
        for(int x=0; x<dim.x; x++){
            printf("%d ", map[y][x]);        
        }
        printf("\n");
    }

    fclose(fichier);
    

The first 3 numbers a read correctly and put into my variables but the matrix is not print correctly, it gives me this:

1 2 3 4 5 11 12 13 14 15
11 12 13 14 15 21 22 23 24 25
21 22 23 24 25 31 32 33 34 35
31 32 33 34 35 41 42 43 44 45
41 42 43 44 45 46 47 48 49 50

I'm working on Windows using minGW32 for compiling if it helps

I tried printing the numbers with a simple

While(fscanf(fichier, "%d", &test)==1){printf("%d",test)}

and it work perfectly printing all the numbers

1 2 3 4 5 6 7 8 ...

Solution

  • Look at these three lines in your code:

    int map[dim.x][dim.y];                       // x, y
    if(fscanf(fichier, "%d ", &map[y][x])!=1){   // y, x
    printf("%d ", map[y][x]);                    // y, x
    

    This is your issue. You create an NxM matrix then treat it as if it's an MxN matrix. That's why it appears to work for the first five elements as they would be the same for both a 10x5 and 5x10 matrix.


    By the way (and this isn't really related to your problem), I think the space in the fscanf format string is superfluous. The %d conversion specifier skips white space before starting to read its integer, and stops reading on the first character not forming part of that integer.