Possible Duplicates:
Don't print space after last number
Printing lists with commas C++
#include <vector> #include <iostream> #include <sstream> #include <boost/foreach.hpp> using namespace std; int main() { vector<int> VecInts; VecInts.push_back(1); VecInts.push_back(2); VecInts.push_back(3); VecInts.push_back(4); VecInts.push_back(5); stringstream ss; BOOST_FOREACH(int i, VecInts) { ss << i << ","; } cout << ss.str(); return 0; }
This prints out: 1,2,3,4,5,
However I want: 1,2,3,4,5
How can I achieve that in an elegant way?
I see there is some confusion about what I mean with "elegant": E.g. no slowing down "if-clause" in my loop. Imagine 100.000 entries in the vector! If that is all you have to offer, I'd rather remove the last comma after I have gone through the loop.
To remove the last comma from a string, call the replace() method with the following regular expression /,*$/ as the first parameter and an empty string as the second. The replace method will return a new string with the last comma removed. Copied!
We can do this with the SPLIT function. This function returns a row of cells divided based on the delimiter. To remove duplicate values, we have to use the UNIQUE function. Since the UNIQUE function works for cells in different rows, we'll have to transpose our SPLIT output using the TRANSPOSE function.
How about this:
#include <iostream> #include <vector> #include <algorithm> #include <iterator> #include <string> #include <sstream> int main() { std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(5); std::ostringstream ss; if(!v.empty()) { std::copy(v.begin(), std::prev(v.end()), std::ostream_iterator<int>(ss, ", ")); ss << v.back(); } std::cout << ss.str() << "\n"; }
No need to add extra variables and doesn't even depend on boost! Actually, in addition to the "no additional variable in the loop" requirement, one could say that there is not even a loop :)
Detecting the one before last is always tricky, detecting the first is very easy.
bool first = true; stringstream ss; BOOST_FOREACH(int i, VecInts) { if (!first) { ss << ","; } first = false; ss << i; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With