Help with matrix reading from a file
Aug 30, 2016 at 1:21pm UTC
How to read matrix from a text file??
Hello I am having trouble to get desired output for reading a 3x3 matrix from a data file
1 2 3 4 5 6 7 8 9 10
FILE *arr;
float k[3][3]={0.0};
arr =fopen("data11.txt" ,"r" );
int i,j;
for (i=0 ;i<3; i++)
for (j=0; j<3; j++)
{
fscanf(arr, "%f%*[^\n]%*c" ,&k[i][j]);
printf("%f\n" , k[i][j]);
}
and data file is::
0 5 10 54 57 58 90 45
2 0 15 1 12 12 0 84
1 3 0 87 48 0 45 9
4 58 4 0 84 95 78 12
output should be ::
0 5 10
2 0 15
1 3 0
instead its showing::
0 5 10
54 57 58
90 45 2
whats the problem here? I am a novice in programming so if anyone can help I would much appriciate it.Thanks in advance.
Aug 30, 2016 at 2:14pm UTC
If you only need the first three elements in the file you still need to read the complete line. Perhaps something like:
1 2 3 4 5 6 7 8 9 10 11
char buffer[1000]
for (i=0 ;i<3; i++)
{
for (j=0; j<3; j++)
{
fscanf(arr, "%f" ,&k[i][j]);
printf("%f " , k[i][j]);
}
printf("\n" );
fgets(buffer, sizeof (buffer), arr);
}
Aug 30, 2016 at 2:23pm UTC
Thanks a lot . Its working
Topic archived. No new replies allowed.