Home:ALL Converter>Specifying the decimal precision for a call to std::copy

Specifying the decimal precision for a call to std::copy

Ask Time:2015-10-13T11:38:00         Author:abcd

Json Formatter

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?

Author:abcd,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/33093691/specifying-the-decimal-precision-for-a-call-to-stdcopy
yy