I need help understanding how to use a Class structure to create a program that reads in two rational numbers and adds them, subtracts, multiplies, and divides them.
I think this is what you're looking for.
Open to suggestions.
I know I'd rather have defined 'math' by pointer for memory-purposes, but this is a small program so I'm not too concerned about it.
#include <iostream>
#include <ifstream>
usingnamespace std;
class doTheMath{
protected:
float a, b;
public:
doTheMath(float, float);
float add() {return a + b;}
float subtract(){return a - b;}
float divide(){return a / b;}
float multiply(){return a * b;}
};
doTheMath::doTheMath(float num1, float num2){
a = num1;
b = num2;
}
int main(){
ifstream file;
float num1, num2;
//****************************************
// This section deals with all the file operations
// It only reads from the file twice
// It doesn't have safeguards against empty files
//****************************************
file.open("my_file.txt");
if(file.fail()) return 0; // If this executes, the program is simply closed
file >> num1; file >> num2;
file.close();
//****************************************
doTheMath math(num1, num2);
// Creates new type from class doTheMath called math
cout << math.add() << endl;
cout << math.subtract() << endl;
cout << math.divide() << endl;
cout << math.multiply() << endl;
return 0;
}
This is great helping me understand the structure of Class thanks!
But this reads in a file. For this program i have to let the user enter two rational numbers at runtime and also have to validate what they have entered is in a fact a number and not junk