0

I am trying to import a matrix in C to then be able to transpose it. When I try to print it, it gives me a 100 by 100 matrix (fills in the blanks with 0's) when it is actually only a 4 by 4. How do I fix this while still keeping the possibility of a bigger matrix in my code? I think the issue might be in my for loops but I can't figure out what to change.

Here is the file I am importing:

4 4
67 23 1 9
7 23 45 98
3 12 4 2
0 0 2 1

PS: I'm french hence the weird names. I added a translation in case it helps better understand my code.

#include stdio.h
#define MAX 100
#define FICHIER_TRANS  "trans.txt" // file_trans

int M[MAX][MAX];
FILE * fichier; // fichier=file

void 
charger () // function to charge the info from the file
{
    int ligne, colonne;  // line, column
 
    if ((fichier = fopen (FICHIER_TRANS, "r")) == NULL)
    {
        printf ("Il y a un probleme pour ouvrir ce fichier"); // there is a problem opening this file
    }
    else
    {
        for (ligne = 0; ligne < MAX && !feof (fichier); ligne++)    
        {
            for (colonne = 0; colonne < MAX && !feof (fichier); colonne++)    
            {
                fscanf (fichier, "%d", &M[ligne][colonne]);
            }
        }
    }
}

void 
afficher () // function to print the matrix taken from the file
{
    int ligne, colonne;
    for (ligne = 0; ligne < MAX; ligne++)    
    {
        for (colonne = 0; colonne < MAX; colonne++) 
        {
            printf ("%3d", M[ligne][colonne]); 
        }
        printf ("\n");   
    }
}

int 
main () 
{
    charger();
    afficher ();
    return 0;
}
Chris
  • 26,361
  • 5
  • 21
  • 42
dery
  • 3
  • 1
  • @bolov It looks like it might help thank you ! – dery Dec 11 '21 at 00:55
  • please format your code properly ... the indent levels are inconsistent ... that makes the code difficult to follow and prone to errors – jsotola Dec 11 '21 at 00:56
  • You're calling feof rather than using the return value of fscanf, which is [always wrong](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Chris Dodd Dec 11 '21 at 06:07

0 Answers0