Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ vector to comma delimitated string? [duplicate]

Tags:

c++

Possible Duplicate:
C++ Vector to CSV by adding Comma after each element

I have a vector:

std::vector<std::pair<int, QString> > recordingArray;

I need to convert it to a comma delimitated string so I can store it in a database (is there a better format for the data - it all needs to go in one field)

How can I convert it to a comma delimitated string?

And then later, convert it back?

like image 346
panthro Avatar asked Dec 10 '12 21:12

panthro


People also ask

How to get comma-separated values from string in c#?

We can get a comma-separated string from an array using String. Join() method. In the same way, we can get a comma-separated string from the integer array. We can also get a comma separated string from the object array, as shown below.

How do you add comma-separated values in an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.


2 Answers

Use std::transform and a std::stringstream for this.

std::stringstream str;

std::transform(
    recordingArray.begin(),
    recordingArray.end(),
    std::ostream_iterator<std::string>(str, ", "),
    [](const std::pair<int, QString> &p) { return std::to_string(p.first) + ", " + p.second.toStdString(); });
like image 187
moswald Avatar answered Sep 26 '22 05:09

moswald


string line = "";
auto it = recordingArray.begin();

while(it != recordingArray.end())
{
  line.append(*it);
  line.append(',');
}

This assumes that each item is directly convertible to a string. You may need to write a toString function.

string toString(std::pair<int, QString>> input)
{
  /* convert the data to a string format */
}

Then call line.append(toString(*it)).

like image 44
lcs Avatar answered Sep 24 '22 05:09

lcs