0
I’m with this C code where the goal is to read 25 whole numbers of a text file and store them in a 5 by 5 array. The problem is that when running on MS-DOS, the program prints only junk from memory. I believe it’s the fgets(...)
. Is there a similar command for integers? Can anyone help in the solution?
Here is an excerpt from the code referring to the problem:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int matriz_A[5][5];
int matriz_B[3][2];
int matriz_C[3][2];
int m, n;
printf("\n Abaixo temos a matriz A \n\n\n");
FILE *matrizA;
matrizA = fopen("matriz_A.txt", "r");
if (matrizA == NULL)
{
printf("\nNão foi possivel abrir o arquivo. \n");
exit(0);
}
while (fgets(matriz_A, 25, matrizA) != NULL);
{
for (m = 0; m<5; m++)
{
for (n = 0; n<5; n++)
{
printf(" %i ", matriz_A[m][n]);
}
printf("\n\n");
}
}
system("pause");
return 0;
}
Exit after run:
The fgets function reads a string of characters until it finds a line end ('n') or reaches the limit of the specified number of characters. If your text file contains numbers you can directly read the numbers with the fscanf function or read the string and then handle the string, for example with the sscanf function.
– anonimo
You can use two loops for (m=0; m<5; m++) for (n=0; n<5; n++) fscanf(matrizA, "%d", &matriz_A[m][n]);
– anonimo