Duplicate Matrix read per file in C

0

I have to read a 48X2 array for a .txt file, the file has this structure:

nome_da_pessoa
1 2
3 4
...
N N

When N is the 47th position element, I need to save the name of the person in a variable, and save the array in another variable, to accomplish this task, I made the following algorithm:

#include<stdio.h>
#include<stdlib.h>
#define Lin 48
#define Col 2
int main(){

    int i, j, Mat[Lin][Col]; 
    char nome[30];
    FILE *arq;

    arq=fopen("matriz.txt", "r");
    fgets(nome, 30, arq);// pega o nome do participante
    for(i=0;i<Lin;i++){
        for(j=0;j<Col;j++){
            fscanf(arq,"%d ", &Mat[i][j]);
            printf("%d ", Mat[i][j]);//testar se a impressão esta correta
    }
    }
    fclose(arq); //fechar arquivo
    return 0;
}

However, when I print the variable Mat[i][j] the program prints the array with the numbers one side of the other, or rather than 48x2. I would like to know what my mistake is, and what I should do.

    
asked by anonymous 23.06.2018 / 22:46

1 answer

1

Your code is missing a \n (it means "new line") in case it would be printf("\n"); after the first one.

It will execute the code knowing that Lin is 48 and Col is 2 he will execute the first one that is the one of the line (48 times) and then it will enter the column for after the 2 columns per line ends there adds \n . (Otherwise it will keep the numbers all in sequence, one on the other side)

Here is an example of the code:

#include<stdio.h>
#include<stdlib.h>
#define Lin 48
#define Col 2
int main(){

    int i, j, Mat[Lin][Col]; 
    char nome[30];
    FILE *arq;

    arq=fopen("matriz.txt", "r");
    fgets(nome, 30, arq);// pega o nome do participante
    for(i=0;i<Lin;i++){
        for(j=0;j<Col;j++){
            fscanf(arq,"%d ", &Mat[i][j]);
            printf("%d ", Mat[i][j]);//testar se a impressão esta correta
    }
    printf("\n");
    }
    fclose(arq); //fechar arquivo
    return 0;
} 
    
24.06.2018 / 03:17