0

I am currently implementing an new software. While parsing a file, I collect a list of line numbers which were skipped. After parsing I would like to output all line numbers as comma separated string.

How can I convert a std::list<int> into a std::string as comma separated list?

Assume this code segment as framework:

#include <list>
#include <string>

void parseFile()
{
    std::list<int> skippedLines;
    // ...parse file...
    if (!skippedLines.empty()) {
        const std::string skippedLinesAsString = ???
        log << "Skipped lines: " << skippedLinesAsString;
    }
}

Please note, I need a std::string as result. The shown stream is just for illustration purposes and can not be used for output.

I implemented it in a traditional way using a loop. But I am sure there is a simple algorithmic solution using a back-inserter or similar.

Flovdis
  • 2,945
  • 26
  • 49
  • @Yakk Actually I use a `QList` which is std library compatible. – Flovdis Aug 20 '15 at 16:04
  • 5
    http://stackoverflow.com/questions/1430757/c-vector-to-string http://stackoverflow.com/questions/5689003/how-to-implode-a-vector-of-strings-into-a-string-the-elegant-way http://stackoverflow.com/questions/5223066/converting-int-to-string-in-c http://stackoverflow.com/questions/2518979/how-to-transform-a-vectorint-into-a-string http://stackoverflow.com/questions/8581832/converting-a-vector-to-string – user4581301 Aug 20 '15 at 16:13
  • 1
    I would stick to a loop writing to a stringstream because it is easily readable and maintainable. You could also look at boost that has a lot of nice tools – Serge Ballesta Aug 20 '15 at 16:14
  • 2
    http://en.cppreference.com/w/cpp/experimental/ostream_joiner is of interest -- in C++1z, you can take a sstream, make a joiner, copy your contents via the joiner, then get the string out of the sstream. – Yakk - Adam Nevraumont Aug 20 '15 at 17:01

1 Answers1

1

Surprisingly enough, there is no good algorithmic solution for this. The general solution would be to use std::stringstream and ostream_iterator, in the following manner:

std::ostringstream str;
std::copy(l.begin(), l.end(), std::ostream_iterator(str, ", ");

The problem is that the last element in the string will be ended with delimter, ', ' in this case. So you will have to do it in the loop if you want proper string.

You could also craft something along the lines of std::accumulate and lambda, but in all honesty, loop will be tons more readable.

SergeyA
  • 61,605
  • 5
  • 78
  • 137