Program only reading first row of Matrix in C

2271 views c

I am trying to read in a 3x3 matrix from a file. The file contains data that looks like this.

5 65 3
3 11 15
22 8 3

So far I have the following code,

int data[3][3];
int i = 0;
int j = 0;
FILE *fptr = fopen("data.txt", "r");

for(; i < 3; ++i){
    fscanf(fptr, "%d %d %d", &(data[i][0]), &(data[i][1]), &(data[i][2]));
i = 0;

for(; i < 3; ++i){
    for(; j < 3; ++j){
        printf("%d ", data[i][j]);


However, only the first line of the matrix is read from the file. When I try printing only the first line is shown followed by two empty lines.

answered question

why don't you initialize j=0 in the inner loop?

Your program code isn't complete and you don't include the output of your program. This means you're missing a complete, verifiable example.

i initialized it in the first line

I would second @Jean-FrançoisFabre's suggestion. Though what you're doing works, it's prone to errors when you forget to reinitialize. Not only does it cut down on lines, it makes the program a lot clearer, and in the case of a reused counter variable, such as i in this case, a lot less prone to bugs ( I realize you reinitialize it in this case).

2 Answers


just write for loops properly:

for(i = 0; i < 3; ++i){
    for(j = 0; j < 3; ++j){

Else, in your case, even if outer loop is ok but inner j loop runs once properly, but since j==3 and isn't reset, it doesn't resume for the next 2 outer iterations.

The 2 last i loops run empty and do nothing.

(and it's not necessary to initialize i and j outside the for statements)

posted this

Try using the below given lines to read the first line of the file & then store the number by separating them.

fscanf(fptr,"%[^\n]", c);

Refer this link for more details

posted this

Have an answer?


Please login first before posting an answer.