使用copy和ostream_iterator删除为向量编写的CSV文件中的结尾逗号 [英] Remove trailing comma in CSV file written for a vector using copy and ostream_iterator

查看:156
本文介绍了使用copy和ostream_iterator删除为向量编写的CSV文件中的结尾逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下功能,该功能将vector写入CSV文件:

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;
}

但是,CSV文件的结尾看起来像这样:

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?

推荐答案

如您所见,通过std::copy复制并不能解决问题,还会输出一个额外的,.有一项建议可能会在将来的C ++ 17标准中使用: ostream_joiner ,它将完全满足您的期望.

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;
}

这篇关于使用copy和ostream_iterator删除为向量编写的CSV文件中的结尾逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆