开发者

One row is skipped each time the program scans a matrix from file !

I had this code working yesterday, but it seems like I edited it a bit and lost the working version. I cant get this to work anymore.

I basically want to scan a matrix from a .txt file. But each time it scans the first row, the second one is skipped, and it reads the third instead :(

Here is my code :

for(i=0;i<=test->rowmat1;i++){
      for(j=0;j<=tes开发者_StackOverflow社区t->colmat1;j++){
        fscanf(fin,"%f\t",&test->mat[i][j]);                                   
      }
     fscanf(fin,"%*[^\n]",&test->mat[i][j]);
   }

For example, for a matrix of :

1.00    2.00    3.00    
4.00    5.00    6.00    
7.00    8.00    9.00    
10.00   11.00   12.00   

If I extract 3 rows and 3 cols, I get :

1.00    2.00    3.00
7.00    8.00    9.00    

Then fails, it wants to skip over the second line but there is nothing after 10 11 12

Why did it stop working ? What do I have wrong ?

@Derek: removing the second scanf, I get for extracting 3 by 3 matrix

1.00    2.00    3.00    
4.00    5.00    6.00    
7.00    8.00    9.00    
10.00   11.00   12.00   

1.00    2.00    3.00    
5.00    6.00    7.00
9.00       10.00    11.00

Last digit is skipped :S

Please help, Thanks in advance.


not an expert on c at all. But when you go to do the second fscand() after the inner loop, won't j be equal to 3?, not 2. How does that effect the fscanf() ?


I think the problem is the loop boundaries. Probably test->colmat1 is 3, since you are reading a matrix with 3 columns. But your inner loop runs four times, since j<=3 is true for j=3. So the inner fscanf() is executed four times, skipping over the first value of the second row. Then the outer fscanf() is executed, and it reads till "\n", so the full second line is ignored.

Probably setting the loop boundaries to

j<colmat

instead of

j<=colmat

solves your problem. Or the same thing with test->colmat instead of colmat.

Also, using j outside of the j loop looks a bit dangerous.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜