#include <iostream>
#include <cstdlib>
#include <cassert>
using namespace std;
class fraction
{
int numer, denom;
public:
fraction(int n = 0, int d = 1) : numer(n), denom(d)
{
assert(denom!=0); // make sure denom is not 0
}
friend ostream& operator<<(ostream& o, const fraction& f)
{
return (o << f.numer << '/' << f.denom);
}
};
int main()
{
int i1, i2;
cout << "Enter two ints => ";
cin >> i1 >> i2;
if (cin.good())
{
fraction f(i1,i2);
cout << f << endl;
}
else cerr << "Bad input\n";
cout << "*** End of Program ***\n";
return 0;
}
First run:
Enter two ints => 1 2 1/2 *** End of Program ***
Second run
Enter two ints => 2 0 Assertion failed: denom!=0, file A:\EX1 1.CPP, line 10 Abnormal program termination
Note: this approach is used to catch a run time error. This is not a compile error. Of course, there are other ways of handling this problem. The author could put a check in main() to verify that the second int entered is non zero. Another approach is to put a check for a denom = 0 in the fraction constructor. The problem, of course, could be "handled" not by aborting the program, but maybe by asking the user for another denominator. This may not always be feasible, since the numerator may not always be supplied by the user. Maybe it's a problem that you want to recognize, but continue the program execution. This is known as fault tolerant processing.