Splitting a stringstream that contains comma separated entries
c++, operator-overloading, stream, string, stringstream
Solution
The istream `>>` operator when applied to a string discards the eventual initial spaces and reads up to the first "space".
It works the same for whatever type (including int). It works in your code because at the ',' the "int reader" fails, and assumes the following is something else.
The simplest way to read comma separated strings is using the `std::getline` function, giving a `','` as a separator.
In your case, your template function
template <typename T>
std::istream &operator>>(std::istream &is, Array<T> &t)
{ ...... }
remains valid, but requires a specialization
std::istream &operator>>(std::istream &is, Array<std::string> &t)
{
std::string r;
while(std::getline(is,r,','))
t.push_back(r);
return is;
}
Problem
I have two strings that look as follows: ``` string text1 = "you,are,good"; string text2 = "1,2,3,4,5"; stringstream t1(text1); stringstream t2(text2); ``` I'm using the following code to to parse it as comma separated data ``` template <typename T> std::istream &operator>>(std::istream &is, Array<T> &t) { T i; while (is >> i) { t.push_back(i); if (is.peek() == ',') is.ignore(); } return is; } ``` where "is" is t1 or t2. This separates text2 but fails with text1. Could you guys please help me with that and tell me why it doesn't work with strings? I need a general code that would parse strings and numbers. Thanks for any efforts :)