how to read from text file and store in matrix in c
c, matrix, text
Solution
Many Issues, consider following, and of course see comments
int main()
{
int i;
int j;
/*matrix*/
/*Use double , you have floating numbers not int*/
double** mat=malloc(1000000*sizeof(double*));
for(i=0;i<1000000;++i)
mat[i]=malloc(4*sizeof(double));
FILE *file;
file=fopen("1234.txt", "r");
for(i = 0; i < 1000; i++)
{
for(j = 0; j < 4; j++)
{
//Use lf format specifier, %c is for character
if (!fscanf(file, "%lf", &mat[i][j]))
break;
// mat[i][j] -= '0';
printf("%lf\n",mat[i][j]); //Use lf format specifier, \n is for new line
}
}
fclose(file);
}
Problem
the first to say is that I'm totally new to coding, so plz forgive my mistakes. I'm now trying to read from a txt file which is rather large, it has about 1000000 lines and 4 cols ``` 56.154 59.365 98.3333 20.11125 98.54 69.3645 52.3333 69.876 76.154 29.365 34.3333 75.114 37.154 57.365 7.0 24.768 ........ ........ ``` I want to read them all and store them into a matrix, here is my code: ``` #include <stdio.h> #include <stdlib.h> #include <malloc.h> int main() { int i; int j; /*matrix*/ int** mat=malloc(1000000*sizeof(int)); for(i=0;i<1000000;++i) mat[i]=malloc(4*sizeof(int)); FILE *file; file=fopen("12345.txt", "r"); for(i = 0; i < 1000; i++) { for(j = 0; j < 4; j++) { if (!fscanf(file, " %c", &mat[i][j])) break; mat[i][j] -= '0'; /* I found it from internet but it doesn't work*/ printf("\n",mat[i][j]); } } fclose(file); } ``` The result is that I got nothing in my matrix. I hope u can help. Thanks in advance for any help.