-1

I am learning c++. I don't understand how to write a long double value in a file. I don't know the number of decimals values, so i think i can't use setprecision. Can you show me hints?

Because this subject is for me a way to understand basic c++, i should only use iostream and fstream.

I don't understand why ofstream decide to truncate my number

long double number=0.12345678987654321012345678987654321012 ..etc;

ofstream myfile("name.txt", ios::binary);

myfile << number ;

It write only 0.1234

Things i tried so far:

myfile << number ;

and

    char     *conversion = reinterpret_cast<char *>(&number );
    myfile << *(reinterpret_cast<double *>(conversion));
    myfile .close();

and

    myfile.write((char *)&resultat, sizeof(long double))  ;
goto
  • 7,908
  • 10
  • 48
  • 58
  • Why can't you just use `std::setprecision` with a suitably large number? Say `20` or `30`? Whatever precision you need. – Galik Jun 11 '15 at 09:38
  • @Galik this is not an answer because it will write excess zeros also. More, you can't guarantee that 20 or 30 is large enough to fit. – VP. Jun 11 '15 at 09:38
  • I'm not sure that it will write excess zeros. Did you try it? But can't you just pick the precision that your application requires? Or what about using [std::numeric_limits/digits10](http://en.cppreference.com/w/cpp/types/numeric_limits/digits10). – Galik Jun 11 '15 at 09:53
  • http://stackoverflow.com/q/1786137/1938163 – Marco A. Jun 11 '15 at 09:54

1 Answers1

3

Solution can be based on numeric limits. You are storing your data in double so use it's numeric limits.

myfile << std::setprecision(std::numeric_limits<double>::digits10 + 2) << number
VP.
  • 15,509
  • 17
  • 91
  • 161
  • this is a static limit, if i understand rigth, it's 12 digits. How could i set it dynamicly? – goto Jun 11 '15 at 11:31
  • Why do you need that? It is a limit that can contain `double` at all. if you store your data in `double` you don't need any more. Also, this will delete excess zeros and you will get proper value. – VP. Jun 11 '15 at 11:35
  • I need that because i'm calculating approximations of Pi. I don't know how much precision i'll need, but it's around thousands. – goto Jun 11 '15 at 11:41
  • You don't have "thousands of digits" of precision in a double, or in a long double. There's no point writing out more digits than the representation can hold, and `std::numeric_limits::digits10` tells you how many digits that would be. – Andrew Jun 11 '15 at 12:04