I have the following function that saves a vector to a CSV file:
#include <math.h>
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <iterator>
using namespace std;
bool save_vector(vector<double>* pdata, size_t length,
const string& file_path)
{
ofstream os(file_path.c_str(), ios::binary | ios::out);
if (!os.is_open())
{
cout << "Failure!" << endl;
return false;
}
copy(pdata->begin(), pdata->end(), ostream_iterator<double>(os, ","));
os.close();
return true;
}
In the resulting CSV file, the numbers in pdata
are saved with variable precision, and none are saved with the precision I want (10 decimal places).
I know about the function std::setprecision
. However, this function, according to the docs,
should only be used as a stream manipulator.
(I'm actually not sure I'm interpreting "stream manipulator" correctly; I'm assuming this means I can't use it in my function as currently written.)
Is there a way for me to specify the decimal precision using the copy
function? If not, how should I get rid of copy
so that I can use setprecision
in the function above?
You can call
os.precision(10);
before the copy.