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?
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.
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.
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(); });
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))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With