So basically I'm trying to make a fraction class. It will take a fraction from user input and perform the addition. For example, I print 1 5 and 1 7, for adding it will print 12/35.
Here is my .h class:
#include <string> #ifndef _FRACTION_H_ #define _FRACTION_H_ using namespace std; class Fraction { public: Fraction(); Fraction(int n, int d); int getNumerator() const; int getDenominator() const; void display(); string to_string(); Fraction operator+(Fraction &second); private: int numerator; int denominator; };
And this is my .cpp file:
#include "Fraction.h" #include <string> include <iostream> using namespace std; Fraction::Fraction(){} Fraction::Fraction(int n, int d) { this->numerator = n; this->denominator = d; } int Fraction::getNumerator() const { return numerator; } int Fraction::getDenominator() const { return denominator; } Fraction Fraction::operator+(Fraction &second) { int n1 = getNumerator() * second.getDenominator(); int n2 = second.getNumerator() * getDenominator(); int d = getDenominator() * second.getDenominator(); return Fraction(n1+n2, d); } string Fraction::to_string() { return (getNumerator() + "/" + getDenominator()) ; }
And this is my main method:
bool get_input(Fraction &fract); int main() { Fraction fraction1, fraction2; if (((!get_input(fraction1)) || (!get_input(fraction2)))) cout << "Invalid Input!" << endl; else { // Test harness for Arithmetic Operator Overloading Fraction result = fraction1 + fraction2; cout << "Addition = " << result.to_string() << endl; } bool get_input(Fraction& fract) { int num, den; cout << "Enter numerator & denominator (separated by space)" << endl; cin >> num >> den; if (cin.fail()) return false; Fraction f(num,den); fract = f; return true; } }
He managed to enter user input. But, however, it does not print the result. Thanks in advance.
source share