C++ Vector to CSV by adding Comma after each element

后端 未结 5 779
梦毁少年i
梦毁少年i 2020-12-18 16:25
vector v;
v.push_back(\"A\");
v.push_back(\"B\");
v.push_back(\"C\");
v.push_back(\"D\");

for (vector::iterator it = v.begin(); it!=v.end()         


        
相关标签:
5条回答
  • 2020-12-18 16:39

    Loop way:

    for (vector<string>::iterator it = v.begin(); it != v.end(); ++it) {
       if (it != v.begin()) cout << ',';
       cout << *it;
    }
    

    "Clever" way:

    #include <algorithm>
    #include <iterator>
    
    if (v.size() >= 2)
       copy(v.begin(), v.end()-1, ostream_iterator<string>(cout, ","));
    if (v.size() >= 1)
       cout << v.back();
    
    0 讨论(0)
  • 2020-12-18 16:40

    To avoid the trailing comma, loop until v.end() - 1, and output v.back() for instance:

    #include <vector>
    #include <iostream>
    #include <iterator>
    #include <string>
    #include <iostream>
    
    template <class Val>
    void Out(const std::vector<Val>& v)
    {
        if (v.size() > 1)
            std::copy(v.begin(), v.end() - 1, std::ostream_iterator<Val>(std::cout, ", ")); 
        if (v.size())
            std::cout << v.back() << std::endl;
    }
    int main()
    {
        const char* strings[] = {"A", "B", "C", "D"};
        Out(std::vector<std::string>(strings, strings + sizeof(strings) / sizeof(const char*)));
    
        const int ints[] = {1, 2, 3, 4};
        Out(std::vector<int>(ints, ints + sizeof(ints) / sizeof(int)));
    }
    

    BTW you posted:

    vector<string> v; 
    //...
    for (vector<int>::iterator it = v.begin(); //...
    

    which is unlikely to compile :)

    0 讨论(0)
  • 2020-12-18 16:46

    You could output the commas in your for loop:

    for (vector<int>::iterator it = v.begin(); it!=v.end(); ++it) {
    //printout 
       cout << *it << ", " << endl;
    }
    

    Or, you could use the copy algorithm.

    std::copy(v.begin(), v.end(), std::ostream_iterator<char*>(std::cout, ", "));
    
    0 讨论(0)
  • 2020-12-18 16:49

    With a normal ostream_iterator, you'll get a comma after every data item -- including the last, where you don't want one.

    I posted an infix_iterator in a previous answer that fixes this problem, only putting commas between the data items, not after the final one.

    0 讨论(0)
  • 2020-12-18 16:54

    Below should do the job. Thanks.

        ofstream CSVToFile("ava.csv", ios::out | ios::binary);
        //////////////////vector element to CSV////////////////////////////////////////
    for (std::vector<string>::iterator i = ParamHeaders.begin(); i != ParamHeaders.end(); i++)
    {
        if (i != ParamHeaders.begin()) 
        {
                CSVToFile << ",";
                std::cout << ",";
        }
        std::cout << *i;
        CSVToFile << *i;
    
    }
    
    0 讨论(0)
提交回复
热议问题