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

前端 未结 3 1803
刺人心
刺人心 2021-01-22 12:46

I have the following function, which writes a vector to a CSV file:

#include 
#include 
#include 
#include         


        
相关标签:
3条回答
  • 2021-01-22 13:05

    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;
    }
    
    0 讨论(0)
  • 2021-01-22 13:06

    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.

    0 讨论(0)
  • 2021-01-22 13:06

    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;
    }
    
    0 讨论(0)
提交回复
热议问题