Doubt in reading Matrix per file in C

Asked

Viewed 1,349 times

0

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

nome_da_pessoa
1 2
3 4
...
N N

Where N is the 47 position elements, I need to save the person’s name in a variable, and save the matrix in another variable, to perform this task, I did 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 printed the matrix with the numbers on each other, or instead of 48x2. I would like to know what my mistake, and what I should do.

  • After the } that closes the for internal, add printf("\n");

  • You don’t even have to do "%d ", with this final blank, in the fscanf() because white spaces are ignored by the function

  • 1

    Ah, got it, I was putting the printf("\n") inside the internal, but there was a number below the other, thank you.

1 answer

1

Your code is missing one \n (means "new line", ie "new line") in case it would look like this printf("\n"); after the first is.

It will run the code knowing that Lin is 48 and Col is 2 it will run the first for that is the row (48 times) and then will enter the column for, after the end of the 2 columns per row you add the \n. (Otherwise it will keep the numbers all in sequence, one on the other side)

Below 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;
} 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.