Remove trailing comma in CSV file written for a vector using copy and ostream_iterator

爷,独闯天下 提交于 2020-06-08 20:01:10

问题


I have the following function, which writes 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;
    }
  os.precision(11);
  copy(pdata->begin(), pdata->end(), ostream_iterator<double>(os, ","));
  os.close();
  return true;
}

However, the end of the CSV file looks like this:

1.2000414752e-08,1.1040914566e-08,1.0158131779e-08,9.3459324063e-09,

That is, a trailing comma is written into the file. This is causing an error when I attempt to load the file using another software program.

What is the easiest, most efficient way to get rid of (ideally, never write) this trailing comma?


回答1:


As you observed, copying via std::copy doesn't do the trick, one additional , is output. There is a proposal that will probably make it in the future C++17 standard: ostream_joiner, which will do exactly what you expect.

However, a quick solution available now is to do it manually.

for(auto it = std::begin(*pdata); it != std::end(*pdata); ++it)
{
    if (it != std::begin(*pdata))
        std::cout << ",";
    std::cout << *it;
}



回答2:


I'd omit printing the comma by treating the first element special:

if (!pdata->empty()) {
    os << pdata->front();
    std::for_each(std::next(pdata->begin()), pdata->end(),
                  [&os](auto&& v){ os << ", " << v; });
}

Obviously, this code goes into a function printing a printable range adapter.




回答3:


There are many ways, besides already listed:

std::string sep;
for (const auto& x : *pdata) {
    os << x << clusAvg;
    sep = ", ";
}

or

auto it = pdata->begin();
if (it != pdata->end()) {
    os << *it;
    for(; it != pdata->end(); ++it)
        os << ", " << *it;
}

or

auto it = pdata->end();
if (it != pdata->begin()) {
    --it;
    std::copy(pdata->begin(), it, ostream_iterator<double>(os, ", "));
    os << *it;
}


来源:https://stackoverflow.com/questions/33094317/remove-trailing-comma-in-csv-file-written-for-a-vector-using-copy-and-ostream-it

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