Printing lists with commas C++

后端 未结 28 2154
时光取名叫无心
时光取名叫无心 2020-11-22 03:33

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 co

28条回答
  •  Happy的楠姐
    2020-11-22 03:52

    One common approach is to print the first item prior to the loop, and loop only over the remaining items, PRE-printing a comma before each remaining item.

    Alternately you should be able to create your own stream that maintains a current state of the line (before endl) and puts commas in the appropriate place.

    EDIT: You can also use a middle-tested loop as suggested by T.E.D. It would be something like:

    if(!keywords.empty())
    {
        auto iter = keywords.begin();
        while(true)
        {
            out << *iter;
            ++iter;
            if(iter == keywords.end())
            {
                break;
            }
            else
            {
                out << ", ";
            }
        }
    }
    

    I mentioned the "print first item before loop" method first because it keeps the loop body really simple, but any of the approaches work fine.

提交回复
热议问题