I would like to copy the contents of a vector
to one long string
with a custom delimiter. So far, I've tried:
// .h string getLabeledPointsString(const string delimiter=","); // .cpp string Gesture::getLabeledPointsString(const string delimiter) { vector<int> x = getLabeledPoints(); stringstream s; copy(x.begin(),x.end(), ostream_iterator<int>(s,delimiter)); return s.str(); }
but I get
no matching function for call to ‘std::ostream_iterator<int, char, std::char_traits<char> >::ostream_iterator(std::stringstream&, const std::string&)’
I've tried with charT*
but I get
error iso c++ forbids declaration of charT with no type
Then I tried using char
and ostream_iterator<int>(s,&delimiter)
but I get strange characters in the string.
Can anyone help me make sense of what the compiler is expecting here?
There is no built-in split() function in C++ for splitting strings, but there are numerous ways to accomplish the same task, such as using the getline() function, strtok() function, find() and erase() functions, and so on. This article has explained how to use these functions to split strings in C++.
C++ '+' operator for String Concatenation C++ '+' operator can be used to concatenate two strings easily. The '+' operator adds the two input strings and returns a new string that contains the concatenated string.
Use delimiter.c_str()
as the delimiter:
copy(x.begin(),x.end(), ostream_iterator<int>(s,delimiter.c_str()));
That way, you get a const char*
pointing to the string, which is what ostream_operator
expects from your std::string
.
C++11:
vector<string> x = {"1", "2", "3"}; string s = std::accumulate(std::begin(x), std::end(x), string(), [](string &ss, string &s) { return ss.empty() ? s : ss + "," + s; });
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