Save & read double vector from file C++

扶醉桌前 提交于 2019-12-11 17:28:54

问题


I'm trying to save a std::vector<double> to a file and read to rebuild the std::vector<double>. This code from rex (original answer) works for std::vector<char> but not for doubles. Once I tried to modify this to work with doubles, numbers lose decimal points. Here is my attempt (modified code)

#include <iostream>
#include <algorithm>
#include <fstream>
#include <iterator>
#include <vector>

std::string filename("savefile");

std::vector<double> myVector{1321.32132,16.32131,32.321,64,3213.454};

void write_vector_to_file(const std::vector<double>& myVector, std::string filename);
std::vector<double> read_vector_from_file(std::string filename);

int main()
{
    write_vector_to_file(myVector, filename);
    auto newVector{read_vector_from_file(filename)};
    //printing output
    std::cout << newVector.at(1) << std::endl;
    return 0;
}

void write_vector_to_file(const std::vector<double>& myVector,std::string filename)
{
    std::ofstream ofs(filename,std::ios::out | std::ofstream::binary);
    std::ostream_iterator<char> osi{ofs};
    std::copy(myVector.begin(),myVector.end(),osi);
}

std::vector<double> read_vector_from_file(std::string filename)
{
    std::vector<double> newVector{};
    std::ifstream ifs(filename,std::ios::in | std::ifstream::binary);
    std::istreambuf_iterator<char> iter(ifs);
    std::istreambuf_iterator<char> end{};
    std::copy(iter,end,std::back_inserter(newVector));
    return newVector;
}

This code outputs 16 instead of 16.32131. What should I do to make this work with doubles? Thank you.


回答1:


This should work:

void write_vector_to_file(const std::vector<double>& myVector, std::string filename)
{
    std::ofstream ofs(filename, std::ios::out | std::ofstream::binary);
    std::ostream_iterator<char> osi{ ofs };
    const char* beginByte = (char*)&myVector[0];

    const char* endByte = (char*)&myVector.back() + sizeof(double);
    std::copy(beginByte, endByte, osi);
}

std::vector<double> read_vector_from_file(std::string filename)
{
    std::vector<char> buffer{};
    std::ifstream ifs(filename, std::ios::in | std::ifstream::binary);
    std::istreambuf_iterator<char> iter(ifs);
    std::istreambuf_iterator<char> end{};
    std::copy(iter, end, std::back_inserter(buffer));
    std::vector<double> newVector(buffer.size() / sizeof(double));
    memcpy(&newVector[0], &buffer[0], buffer.size());
    return newVector;
}

The problem was that doubles where being cast to char before storing.



来源:https://stackoverflow.com/questions/46663046/save-read-double-vector-from-file-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!