Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- using namespace std;
- class Fraction
- {
- private:
- double p, q;
- public:
- Fraction(double a = 0, double b = 1){p=a; q=b;};
- void print(){cout<<p<<"/"<<q;};
- Fraction sum(Fraction f){return Fraction(p*f.q+f.p*q, q*f.q);};
- Fraction sum(double d){return sum(Fraction(d, 1));};
- Fraction operator+(Fraction f){return sum(f);};
- Fraction operator+(double d){return sum(d);};
- Fraction operator=(const Fraction & f){p = f.p; q = f.q;};
- void setP(double value){p=value;};
- void setQ(double value){q=value;};
- double getP(){return p;};
- double getQ(){return q;};
- friend ostream & operator << (ostream & os, const Fraction & f);
- friend istream & operator >> (istream & is, Fraction & f);
- bool saveToFile(const string & filename)const;
- bool loadFromFile(const string & filename);
- };
- int main()
- {
- Fraction temp1, temp2;
- cin >> temp1;
- cout << temp1 << endl;
- string filename = "temp.txt";
- cout << "Saving to file " << filename << endl;
- temp1.saveToFile(filename);
- cout << "Loading from file " << filename << endl;
- temp2.loadFromFile(filename);
- cout << temp2 << endl;
- }
- bool Fraction::saveToFile(const string & filename)const
- {
- std::ofstream fout(filename);
- if (!fout)
- return false;
- fout<<*this;
- return true;
- }
- bool Fraction::loadFromFile(const string & filename)
- {
- ifstream fin(filename);
- if (!fin)
- return false;
- fin>>*this;
- return true;
- }
- ostream & operator << (ostream & os, const Fraction & f)
- {
- os << f.p;
- if (f.q != 1)
- os << "/" << f.q;
- return os;
- }
- istream & operator >> (istream & is, Fraction & f)
- {
- string input;
- is >> input;
- int pos = input.find('/');
- string left, right;
- if (pos == -1)
- {
- left = input; right = "1";
- }
- else
- {
- left = input.substr(0, pos);
- right = input.substr(pos+1);
- }
- f.setP(stod(left)); f.setQ(stod(right));
- return is;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement