Rewrite the loops the following way
for(i = 0; i < 10; i++)
{
for(j = 0; j < 10; j++)
{
fscanf(fr, "%d",&matrix[i][j]);
printf("%3d ", matrix[i][j]);
}
printf( "\n" );
}
Domanda
This is the code which read a matrix 10x10 from a file "F1.txt"
#include <stdio.h>
int main( int argc, char ** argv ) {
FILE * fr;
fr = fopen("F1.txt","r");
int i, j;
int matrix[10][10] = {0.0};
for(i = 0; i < 10; i++)
{
for(j = 0; j < 10; j++)
{
fscanf(fr, "%d",&matrix[i][j]);
printf("%d\n", matrix[i][j]);
}
}
getchar();
return 0;
}
"F1.txt" looks like this:
12 343 34 544 43 32 124 52 212 3
12 343 34 544 43 32 124 52 212 3
12 343 34 544 43 32 124 52 212 3
12 343 34 544 43 32 124 52 212 3
12 343 34 544 43 32 124 52 212 3
12 343 34 544 43 32 124 52 212 3
12 343 34 544 43 32 124 52 212 3
12 343 34 544 43 32 124 52 212 3
12 4 34 56 43 32 124 52 212 3
32 343 34 544 43 32 7 52 456 98
It works without problems but the output is:
12
343
34
544
43
32
124
52
212
3
12
343
34
544
43
32
124
52
212
..........
etc....
I have to detect the end of line to make my input the same like in F1.txt
12 343 34 544 43 32 124 52 212 3
12 343 34 544 43 32 124 52 212 3
12 343 34 544 43 32 124 52 212 3
12 343 34 544 43 32 124 52 212 3
12 343 34 544 43 32 124 52 212 3
12 343 34 544 43 32 124 52 212 3
12 343 34 544 43 32 124 52 212 3
12 343 34 544 43 32 124 52 212 3
12 4 34 56 43 32 124 52 212 3
32 343 34 544 43 32 7 52 456 98
.
Soluzione
Rewrite the loops the following way
for(i = 0; i < 10; i++)
{
for(j = 0; j < 10; j++)
{
fscanf(fr, "%d",&matrix[i][j]);
printf("%3d ", matrix[i][j]);
}
printf( "\n" );
}
Altri suggerimenti
You are reading the data correctly, but you are not printing it right. Your program inserts '\n'
after each character, that's why you see so many lines.
Change your program like this to see the output that you expect:
for(i = 0; i < 10; i++)
{
for(j = 0; j < 10; j++)
{
fscanf(fr, "%d",&matrix[i][j]);
printf("%d ", matrix[i][j]); // <<== Replace \n with a single space
}
printf("\n"); // <<== Add this line
}
Or if you just want your input formatted, you can write your end of line in the outer loop on i
.
for(i = 0; i < 10; i++)
{
for(j = 0; j < 10; j++)
{
fscanf(fr, "%d",&matrix[i][j]);
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
For your knowledge, EOL is usually a LF
character or combination of CR-LF
characters. In C they are represented by \n
or \r\n
respectively.
A possible solution is that you can use fgets
to read a complete line at once (fgets
will read one line only by itself). Then read out the integers from that string using sscanf
or strtok
.
I suggest you to use sscanf
if you know number of integers in every line.
Otherwise, if a line can contain any amount of numbers then you can use strtok
with " "
(space) as the delimitter.
You can read more about these functions here: sscanf
, strtok
fscanf(fr, "%d",&matrix[i][j]);
printf("%d", matrix[i][j]);
if(j < 10-1)
printf(" ");
else
printf("\n");