Could somone give me a hint as to why my division by 0 check doesn't work?

``````istream & operator >> ( istream & is , Rational & r )
{
char x ;
is >> r.num >> x >> r.den ;
if ( r.den == '0' )
{
cout << "Division by '0' impossible - Exiting program" << endl ;
exit ( 1 ) ;
}
return is;
}``````

x should be the '/' symbol

## All 5 Replies

Problem # 2; here's my header file:

``````#pragma once

#include <iostream>
using namespace std ;

class Rational
{
public:
Rational ( int , int ) ;
Rational ( int ) ;
Rational ( ) ;

void normalize ( ) ;
friend ostream & operator << ( ostream & os , const Rational & r ) ;
friend istream & operator >> ( istream & is , const Rational & r ) ;
private:
int num ;
int den ;
} ;

Rational::Rational ( int x , int y ) : num ( x ) , den ( y )
{ /*Body intentionally empty*/ }

Rational::Rational ( int x ) : num ( x ) , den ( 0 )
{ /*Body intentionally empty*/ }

Rational::Rational ( ) : num ( 0 ) , den ( 0 )
{ /*Body intentionally empty*/ }

ostream & operator<< ( ostream & os , const Rational & r )
{
os << r.num << "/" << r.den ;
return os;
}

istream & operator >> ( istream & is , const Rational & r )
{
char x ;
is >> r.num >> x >> r.den ;
if ( r.den == '0' )
{
cout << "Division by '0' impossible - Exiting program" << endl ;
exit ( 1 ) ;
}
return is;
}
``````

At line 36 I added the word const and now when I run the program it waits about 2 seconds and says Process is terminated due to StackOverflowException and craps out

Could somone give me a hint as to why my division by 0 check doesn't work?

You're not checking for division by 0 -- you're checking for division by '0'.

At line 36 I added the word const

Why would you make if const if you're going to modify it?

Oh, ok. Thanks!

:self-esteem lowered by 2 points:

Ok, I know how to check inequalities for postitive rational numbers:

if ad < cb then a/b < c/d

but what do I do if b or d is negative?

Ok, I got it but not sure I did it the most efficient way:

``````bool operator < ( const Rational & r1, const Rational & r2 )
{
if ( r1.den < 0 && r1.num > 0 && r2.den > 0 && r2.num > 0 )
return true ;
else if ( r1.den > 0 && r2.den < 0 && r2.num > 0 && r1.num > 0 )
return false ;

if ( r1.num * r2.den < r2.num * r1.den )
return true ;
else
return false ;
}``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.