开发者

fscanf: reading a ',' instead of '\n'

开发者 https://www.devze.com 2023-01-12 07:29 出处:网络
i\'m reading a file which contains data such as this: 1,1 0.5,0.5 2,2 these are vectors, all numbers are double.

i'm reading a file which contains data such as this:

1,1
0.5,0.5
2,2

these are vectors, all numbers are double.

since in my exercise the length of each vector is开发者_如何学运维 known, i'm using a for loop to read each vector:

    for (i=0; i<NUM; i++) {  //number of vectors to read
        for (j=0; j<DIM; j++) {  //length of each vector
        fscanf(fp,"%lf,",&x._x[j]);
    }
}  

well this works, it actually reads all three vectors. However, i'm not sure about the reading pattern.

my question is, is it ok to read each vector with "%lf," since at the end of each vector there is actually "\n" and not ",".. Would it be better to read the last coordinate of each vector with "%lf\n"?

thanks!


Your problem is due to the fact the last number is not followed by a comma. So you have to do something like

for (i=0; i<NUM; i++) {  //number of vectors to read
    for (j=0; j<DIM-1; j++) {  //length of each vector
        fscanf(fp,"%lf,",&x._x[j]);
    }
    fscanf(fp,"%lf",&x._x[j]);
}
0

精彩评论

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