开发者

Writing a double type value to a text file

The below code is writing unreadable characters to the text file:

int main () 
{
    ofstream myfile ("example.txt");

    if (myfile.is_open())
    {
        double value       = 11.23444556;
        char   *conversion = (char *)&value;
        strcat (conversion, "\0");

        myfile.write (conve开发者_运维百科rsion, strlen (conversion));
        myfile.close();
    }   

    return 0;
}

I want to see the actual number written in the file :( Hints please.

EDIT Seeing the answers below, I modified the code as:

int main () 
{
    ofstream myfile ("example.txt");

    if (myfile.is_open())
    {
        double value       = 11.23444556;

        myfile << value;
        myfile.close();
    }   

    return 0;
}

This produces the putput: 11.2344 while the actual number is 11.23444556. I want the complete number.

Editing the post to notify everyone: The unreadable characters are due to ofstream's write function:

This is an unformatted output function

This quote is from: http://www.cplusplus.com/reference/iostream/ostream/write/


Why don't you simply do this (updated answer after the edit in the question):

 #include <iomanip>

 myfile << std::fixed << std::setprecision(8) << value;
 myfile.close();

Now, you can see the actual number written in the file.

See the documentation of std::setprecision. Note: you have to include the <iomanip> header file.


It's easier here to use the stream operators:

#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;

int main () 
{
    ofstream myfile ("example.txt");

    if (myfile.is_open())
    {
        double value       = 11.23444556;

        myfile << value;
        myfile.close();
    }   

    return 0;
}

gives you what you want.


Others suggested better ways but if you really want to do it the pointer way there should be casts to convert char* to double * and vice versa

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;

int main () 
{
  ofstream myfile ("example.txt");
  if (myfile.is_open())
  {
    double value       = 11.23444556;
    char     *conversion = reinterpret_cast<char *>(&value);
    strcat (conversion, "\0");
    //myfile.write (*conversion, strlen (conversion));
    myfile << *(reinterpret_cast<double *>(conversion));
    myfile.close();
  }
  return 0;
}


You can write the value to file like this:

myfile << value;

Using the adress of value as parameter strcat corrupts your stack, since strcat expects a 0-terminated c-string as first argument (and actually allocated space).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜