The istream operator here is being overloaded and im not sure what the TODO mean
ID: 3862925 • Letter: T
Question
The istream operator here is being overloaded and im not sure what the TODO mean. I looked up what peek does but i dont know how to use it in this situation. Please help
// TODO: Make this read integer values if no '/' is given as a separator.
// You may assume that there is no space between the numerator and the
// slash. Hint, find and read the reference documentation for istream::peek().
std::istream&
operator>>(std::istream& is, Rational& r)
{
int p, q;
char c;
is >> p >> c >> q;
if (!is)
return is;
// Require that the divider to be a '/'.
if (c != '/') {
is.setstate(std::ios::failbit);
return is;
}
// Make sure that we didn't read p/0.
if (q == 0) {
is.setstate(std::ios::failbit);
return is;
}
r = Rational(p, q);
return is;
}
Explanation / Answer
std::istream& inp(std::istream& is, Rational& r)
{
if (!is)
return is;
int p, q;
char c;
is >> p;
c = is.peek(); // peek character
if ( c == '/' )
{
cin >> c >> q;
if (q == 0) {
is.setstate(std::ios::failbit);
return is;
}
}
else
{
c = '/';
q = 1;
}
cout << p <<c <<q << endl;
r = Rational(p, q);
return is;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.