Printing lists with commas C++

2018-12-31 07:54发布

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.

24条回答
牵手、夕阳
2楼-- · 2018-12-31 08:53

Try this:

typedef  std::vector<std::string>   Container;
typedef Container::const_iterator   CIter;
Container   data;

// Now fill the container.


// Now print the container.
// The advantage of this technique is that ther is no extra test during the loop.
// There is only one additional test !test.empty() done at the beginning.
if (!data.empty())
{
    std::cout << data[0];
    for(CIter loop = data.begin() + 1; loop != data.end(); ++loop)
    {
        std::cout << "," << *loop;
    }
}
查看更多
高级女魔头
3楼-- · 2018-12-31 08:56

Something like this?

while (iter != keywords.end())
{
 out << *iter;
 iter++;
 if (iter != keywords.end()) cout << ", ";
}
查看更多
浪荡孟婆
4楼-- · 2018-12-31 08:56

I suggest you simply switch the first character with the help of a lambda.

std::function<std::string()> f = [&]() {f = [](){ return ","; }; return ""; };                  

for (auto &k : keywords)
    std::cout << f() << k;
查看更多
ら面具成の殇う
5楼-- · 2018-12-31 08:56

Using boost:

std::string add_str("");
const std::string sep(",");

for_each(v.begin(), v.end(), add_str += boost::lambda::ret<std::string>(boost::lambda::_1 + sep));

and you obtain a string containing the vector, comma delimited.

EDIT: to remove the last comma, just issue:

add_str = add_str.substr(0, add_str.size()-1);
查看更多
梦该遗忘
6楼-- · 2018-12-31 08:56

I would go with something like this, an easy solution and should work for all iterators.

int maxele = maxele = v.size() - 1;
for ( cur = v.begin() , i = 0; i < maxele ; ++i)
{
    std::cout << *cur++ << " , ";
}
if ( maxele >= 0 )
{
  std::cout << *cur << std::endl;
}
查看更多
人气声优
7楼-- · 2018-12-31 08:58

Another possible solution, which avoids an if

Char comma = '[';
for (const auto& element : elements) {
    std::cout.put(comma) << element;
    comma = ',';
}
std::cout.put(']');

Depends what you're doing in your loop.

查看更多
登录 后发表回答