Reading number from file

I know this is a rocky problem but I can't seam to find a solution for it.
I am trying to read a number (lets say 0.2) from file with the code below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "std_lib_facilities.h"

int main(){
    double value=0;

    ifstream ist("test.txt");
    if(!ist) error("Could not open test.txt");
    if(ist) cout << "File open!" << endl;
    ist >> value;
    cout << value << endl;
    cout.precision(30);
    cout << value << endl;
    return 0;
}


The fist instance for cout had me assume that everything is ok but the second call with a higher precision reveals the problem. The value stored is not the one in the file.
Is there anything I can do to prevent that? How do I get the stored value to be 0.2?

Thanks for your help!
If you mean that the second output is some number very close to 0.2, but not exactly 0.2, then welcome to computers.

http://floating-point-gui.de/
Thanks. That link looks promising. I just hope ill get it.
I think I have now understood the underlying problem. But there is something I am still a bit concerned about.
My specific problem was (or is) the comparison of two values. regarding them being equal I have used the method described here (http://floating-point-gui.de/errors/comparison/ ).

My concern is now whether or not it is possible that a comparison as a<b delivers a wrong result.
My feeling is that that should be impossible as long as a and b are of the same type (lets say float). However if I for some reason compare a double to an int I would feel that it could come to problems due to the nearest approximation of the number represented as a double changes the outcome. Could this be the case?

Thanks!
Last edited on
I have found that my concerns are actually justified. In fact I have two doubles that show something very similar. The one is red from file and should be 0.19 and instead ends up to be (a) 0.18999..., the other one is the sum of a few numbers (all read from the same file) and should (in this case) also be 0.19 but instead turns out to be (b) 0.19000001 instead.

I guess this implies that one always has to first check if a==b (as described above - link) before one checks a<b or a>b. Comparisons as a>=b would not be advisable as they would, in this case deliver an undesired outcome!!

Would you agree?
Last edited on
Topic archived. No new replies allowed.