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()
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();
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 :)
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, ", "));
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.
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;
}