error when writing some double to binary using seekp and write

Here is the code. I notice the first number 57.98 cannot shown correctly. After reading in hex I find out that 57.98 converted to 9 bytes when I write in to the file. How can I fix this?

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;
int main()
{
    fstream f("Test.dat");

    // Defining a vector to write
    vector<double> data = { 57.98, 11.99, 11.00, 79.50, 99.99, 6.99, 21.50, 7.50 };

    for (size_t i = 0; i < data.size(); i++) {
        f.seekp(static_cast<int64_t>(i) * sizeof(double));
        f.write(reinterpret_cast<char*>(&data.at(i)), sizeof(double));
    }
    
    for (size_t i = 0; i < data.size(); i++) {
        double d;
        f.seekg(static_cast<int64_t>(i) * sizeof(double));
        f.read(reinterpret_cast<char*>(&d), sizeof(double));
        cout << d << ", ";
    }

    f.close();

    return 0;
}
Output: 
8.62172e+285, 11.99, 11, 79.5, 99.99, 6.99, 21.5, 7.5,


Read more here: https://stackoverflow.com/questions/66275571/error-when-writing-some-double-to-binary-using-seekp-and-write

Content Attribution

This content was originally published by Monster030 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: