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 🙂
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::getlinefunction, giving a','as a separator.In your case, your template function
remains valid, but requires a specialization