What is wrong with this overloaded operator?
I am trying to parse a stringstream
to an object which has the members a
, b
and c
as integers.
istream& operator>> (istream& in, Feedback& object) {
cout << __PRETTY_FUNCTION__ << endl;
in >> object.a;
in >> object.b;
in >> object.c;
cout << object.a << " " << object.b << " " << object.c << endl;
return in;
}
The last cout
is printing 0 for all members.
I can see that the stringstream
is properly filled before the input operator in this code...
cout << __PRETTY_FUNCTION__ << ": " << ss.str().c_str() << endl;
ss >> feedback;
this cout
prints:
Feedback parseFeedbackData(unsigned char*, int): 10 2 4
The output overloaded operator is working fine. You can find the code below:
ostream& operator<< (ostream& out, Feedback& object) {
cout << __PRETTY_FUNCTION__ << endl;
out << object.a << " " << object.b << " " << object.c;
return out;
}
The output of ss.str().c_str()
does not necessarily give a clue as to what the other states of the istringstream
object are.
You should add tests to make sure that the reads are successful.
istream& operator>> (istream& in, Feedback& object) {
cout << __PRETTY_FUNCTION__ << endl;
if ( !(in >> object.a) )
{
cout << "Problem reading a\n";
return in;
}
if ( !(in >> object.b) )
{
cout << "Problem reading b\n";
return in;
}
if ( !(in >> object.c) )
{
cout << "Problem reading c\n";
return in;
}
cout << object.a << " " << object.b << " " << object.c << endl;
return in;
}
This will help you figure out where the problem lies.
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.