Alex Rivera | Logout

Writing a double type value to a text file

Asked 2011-06-03T10:58:45.447
12

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 (conversion, 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/

Edit
Report

1 Answer

3

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.

answered 2011-06-03T11:03:01.563

Your Answer