I am trying to read rational number like this (5/9) here is the property of this
ID: 3636142 • Letter: I
Question
I am trying to read rational number like this (5/9)here is the property of this class
class CRational
{
public:
CRational(int numerator = 0, int denominator = 1)
: m_numerator(numerator), m_denominator(denominator)
private:
// properties
int m_numerator;
int m_denominator;
void setProperForm(void);
int LCD(const CRational &other) const;
};
ostream& operator<<(ostream& sout, const CRational &rationalNumber);
istream& operator>>(istream& sin, CRational& rationalNumber);
}
}
here is my code for istream &operator>>, is not working please help
istream& operator>>(istream& sin, CRational& rationalNumber)
{
char space = ' ';
int numerator = 0;
int denominator = 0;
double num = 0.0;
ostringstream output;
if(!(output << num))
throw exception("error");
bool rationalNum = true;
for(int i = 0; i < output.str().length(); i++)
{
if(output.str()[i] == '.')
rationalNum = true;
}
if(rationalNumber)
{
if(output.str().length() >= 3)
throw exception("maximun is 2");
else
{
CRational(num);
return sin;
}
}
//sin >> numerator;
if(!(sin >> numerator))
return sin;
while(isspace(space = sin.peek()) && space != ' ')
{
sin.get();
}
if(space == '/')
sin.get();
denominator = 1;
sin >> denominator;
rationalNumber.setnumerator(numerator);
rationalNumber.setdenominator(denominator);
return sin;
}
Explanation / Answer
you can try with the following istream &operator >>(istream &stream, Rational &n) { stream >> n.a; stream >> n.b; return stream; }//end Rat >> ostream &operatorRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.