mardi 10 octobre 2017

Save & read double vector from file C++

I'm trying to save a std::vector<double> to a file and read to rebuild the std::vector<double>. This code block 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.

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

std::string filename("savefile");

std::vector<char> myVector{1,16,32,64};

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

int main()
{
    write_vector_to_file(myVector, filename);
    auto newVector{read_vector_from_file(filename)};
    return 0;
}

void write_vector_to_file(const std::vector<char>& 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<char> read_vector_from_file(std::string filename)
{
    std::vector<char> 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;
}

What should I do to make this work with doubles? Thank you.

Aucun commentaire:

Enregistrer un commentaire