我有以下函数,它写了一个 vector
到一个CSV文件。
#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文件的结尾是这样的。
1.2000414752e-08,1.1040914566e-08,1.0158131779e-08,9.3459324063e-09,
就是说,一个尾部的逗号被写进了文件。 当我试图使用其他软件程序加载文件时,这会导致一个错误。
有什么最简单、最有效的方法可以去掉(最好是永远不写)这个尾部的逗号?
正如你所看到的,通过 std::copy
还不行,还得多加一个 ,
是输出。有一个提案可能会被写入未来的C++17标准中。ostream_joiner
,它将完全按照你的期望来做。
然而,现在有一个快速的解决方案是手动完成。
for(auto it = std::begin(*pdata); it != std::end(*pdata); ++it)
{
if (it != std::begin(*pdata))
std::cout << ",";
std::cout << *it;
}
我会通过将第一个元素特殊处理来省略打印逗号。
if (!pdata->empty()) {
os << pdata->front();
std::for_each(std::next(pdata->begin()), pdata->end(),
[&os](auto&& v){ os << ", " << v; });
}
很明显,这段代码会进入一个打印可打印范围适配器的函数。
除了已经列出的,还有很多方法。
std::string sep;
for (const auto& x : *pdata) {
os << x << clusAvg;
sep = ", ";
}
或者...
auto it = pdata->begin();
if (it != pdata->end()) {
os << *it;
for(; it != pdata->end(); ++it)
os << ", " << *it;
}
或
auto it = pdata->end();
if (it != pdata->begin()) {
--it;
std::copy(pdata->begin(), it, ostream_iterator<double>(os, ", "));
os << *it;
}