tags:

views:

32

answers:

1

Hello everyone,

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!

+1  A: 

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]);
}
Dacav
there is not need to place \n? i mean in last line: fscanf(fp,"%lf\n",...)
rob
No. scanf-like functions simply ignore \n. \n is relevant only with respect to buffering (i.e. the input gets read when \n is inserted)
Dacav
I understand.. thanks for the quick answer
rob
You are welcome. If the solution is good for your application, you may consider accepting it as correct answer (enable the green "tick" just below the voting control on the left)
Dacav
If you include the `\n` (or any whitespace character) at the end, `fscanf` will consume the following whitespace immediately. If you don't, it will consume the preceding whitespace at the beginning of the next call. Unless you're interspersing calls to other functions that operate on the `FILE`, it makes no difference.
R..