I would like to parse a comma-separated-value string with a stringstream without having to call stringstream::ignore() for each value.
std::string csvString = "1,2,3,4";
int i1, i2;
std::stringstream ss(csvString);
ss >> i1;
ss >> i2;
if (ss.fail())
throw "failed!"
Most tutorials about overloading the insertion operator use a user defined type as the the right hand operand. I have seen a few other examples. I suppose the solution would look something like this:
class ParserStream
{
private:
std::stringstream & m_ss;
public:
ParserStream(std::stringstream & ss): m_ss(ss){}
template<typename T>
ParserStream & operator>>(T val)
{
m_ss >> val;
m_ss.ignore();
return *this;
}
};
It doesn't work. How could it work?
As cigien said in the comments, the problem was that the right hand side parameter is not passed by reference. The following code works correctly:
template<typename T>
ParserStream & operator>>(T & val)
{
m_ss >> val;
m_ss.ignore();
return *this;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.