I am learning C++ and am doing a project dealing with a class that represents rational numbers (such as ½). I have overloaded the istream >>
operator so that it correctly reads rational numbers from the stream.
I am having an issue with taking in an integer into the stream for a rational number. For example if someone types 2 I want it to be read from the stream as 2/1. I have been told using the peek()
function would work but I cannot figure out how. Here is the code:
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;
}
It works perfectly unless an integer is input; I want it to be read as (int)/1
.
Any suggestions?