I know how to do this in other languages, but not C++, which I am forced to use here.
I have a Set of Strings that I'm printing to out in a list, and they need a comma between each one, but not a trailing comma. In java for instance, I would use a stringbuilder and just delete the comma off the end after I've built my string. How do I do it in C++?
auto iter = keywords.begin();
for (iter; iter != keywords.end( ); iter++ )
{
out << *iter << ", ";
}
out << endl;
I initially tried inserting this block to do it (moving the comma printing here)
if (iter++ != keywords.end())
out << ", ";
iter--;
I hate when the small things trip me up.
EDIT: Thanks everyone. This is why I post stuff like this here. So many good answers, and tackled in different ways. After a semester of Java and assembly (different classes), having to do a C++ project in 4 days threw me for a loop. Not only did I get my answer, I got a chance to think about the different ways to approach a problem like this. Awesome.
This one overloads the stream operator. Yes global variables are evil.
There is a little problem with the
++
operator you are using.You can try:
This way,
++
will be evaluated before compare the iterator withkeywords.end()
.Following should do:-
Can use functors:
Example:
Because everyone has decided to do this with while loops, I'll give an example with for loops.
I think this should work