Reputation: 469
I have overloaded the >>
operator, making an object from a stream. I was wondering if I can use this in a contructor that takes in the same format as the stream but as a string. Could I use the >>
operator in the constructor, or will I have to make code to split that line up differently?
For example:
Person::Person(std::string line)
{
// this doesn't work
this >> line;
}
std::istream &operator>>(std::istream &is, Person &p)
{
char c1;
std::string forename, surname;
if (is >> forename >> c1 >> surname)
{
if (c1 == ',')
{
p.forename = forename;
p.surname = surname;
}
else
{
is.clear(std::ios_base::failbit);
}
}
return is;
}
An example input would be: Foo,Bar
Upvotes: 1
Views: 68
Reputation: 38498
#include <sstream>
Person::Person(std::string line)
{
std::stringstream ss(line);
ss >> *this;
}
Upvotes: 4