C++ Operator Overload << and >> operators for files

Description

C++ Operator Overload << and >> operators for files

#include <fstream>
#include <iostream>
using namespace std;
class Measure/* ww  w  . j  a  v a  2s .  c  o m*/
{
   private:
   int feet;
   float inches;
   public:
   Measure() : feet(0), inches(0.0)
   {  }
   Measure(int ft, float in) : feet(ft), inches(in)
   {  }
   friend istream& operator >> (istream& s, Measure& d);
   friend ostream& operator << (ostream& s, Measure& d);
};
istream& operator >> (istream& s, Measure& d)  //get Measure
{                                            //from file or
    char dummy;  //for ('), (-), and (")         //keyboard
    s >> d.feet >> dummy >> dummy >> d.inches >> dummy;
    return s;
}
ostream& operator << (ostream& s, Measure& d)  //send Measure
{                                            //to file or
    s << d.feet << "\'-" << d.inches << '\"';    //screen with
    return s;                                    //overloaded
}                                            //<< operator
int main()
{
    char ch;
    Measure dist1;
    ofstream ofile;                     //create and open
    ofile.open("DIST.DAT");             //output stream
    do {
        cout << "\nEnter Measure: ";
        cin >> dist1;                    //get distance from user
        ofile << dist1;                  //write it to output str
        cout << "Do another (y/n)? ";
        cin >> ch;
    } while(ch != 'n');
    ofile.close();                      //close output stream
    ifstream ifile;                     //create and open
    ifile.open("DIST.DAT");             //input stream
    cout << "\nContents of disk file is:\n";
    while(true)
    {
        ifile >> dist1;                  //read dist from stream
        if( ifile.eof() )                //quit on EOF
            break;
        cout << "Measure = " << dist1 <<endl;
    }
    return 0;
}



PreviousNext

Related