read long double from a file, then write to another file

113 views Asked by At

i have following part of code:

string v;

getline(linestream,v,' ');

double d=atof(v.c_str());

fprintf(writeFile3,"%f\n",(double)d);   

but lets say first line has value 0.08012901 but d=0.080129 last 2 values are omitted, how can i get full double value?

Thank you

3

There are 3 answers

0
Daniel On BEST ANSWER

It's not that the decimal places are not stored in the d. It's just that fprintf only prints 6 decimal places by default. To print 8, try

fprintf(writeFile3, "%.8f\n", d);

You don't have to cast d as a double since it already is of type double.

1
Jerry Coffin On

If you want the digits copied exactly, by far the easiest way to go is to just leave the digits in string form:

string v;

getline(instream, v, ' ');

outstream << v;

Almost anything that converts the digits to a double, then prints out the value has at least some chance of producing a result that's slightly different from the input.

0
clarkatron On

I would add to the answer above that whatever you put after the variable call is what you will display. By default C++ will show 6.

ie fprintf(writeFile3, "%.3f\n", (double)d); will display 3 decimal points at the end. It will also pad so if there is possible for longer than 8 decimal places you will want to make it more than that. That I know of you cannot set a flag to just display all decimal points. It has to be explicit.