I have a class for working with rational numbers with three files and my goal is to be able to satisfy this output
correct output:
Enter operator (+,-,*,/,==,>=,<=,!=,<,>,-1 for negation): -
Enter the two operands (ex. 1/2 or -3/4): 2/3 3/8
(2/3)-(3/8)=7/24
Everything works fine except a runtime error where the second rational for some reasons defaults to 0/1, which I think means the second number isn't being accepted.
my output:
Enter operator (+,-,*,/,==,>=,<=,!=,<,>,-1 for negation): +
Enter the two operands (ex. 1/2 or -3/4): 2/3 3/8
(2/3)+(0/1)= 2/3
Any help is appreciated!
RATIONAL.h
friend istream& operator >> (istream& ins, Rational &r);
RATIONAL.cpp
istream& operator >> (istream& ins, Rational &r)
{
bool isnegative = false, slashfound = false, isvalid = true;
string str;
ins >> str;
int i;
for(i = 0; i < str.length(); i++)
{
if(str[i] == '-')
{
if (i != 0)
isvalid = false;
else
isnegative = true;
}
else if(str[i] == '/')
{
if(i = 0 || (i == str.length()-1) || (isnegative && i == 1) || slashfound)
isvalid = false;
else
slashfound = true;
}
else if(!isdigit(str[i]))
isvalid = false;
if(!isvalid)
{
ins.setstate(ios::failbit);
return ins;
}
istringstream istr(str);
if (slashfound)
{
int n, d;
char c;
istr >> n >> c >> d;
if(d == 0)
{
ins.setstate(ios::failbit);
}
else
{
r.numerator = n;
//r.denominator = 1; // slashfound
r.denominator = d;
}
}
else // case where slash not found
{
istr >> r.numerator;
r.denominator = 1;
}
}
return ins;
}
MAIN.cpp
cout << "Enter the two operands: ";
cin >> r1 >> r2;
picture for convenience and assume all header files are in code etc