Headlines
Loading...
C++ PROGRAM  Overloading << and >> operators for files

C++ PROGRAM Overloading << and >> operators for files

/*PROGRAM :  Overloading << and >> operators for files*/


#include<iostream.h>

#include<conio.h>

#include<fstream.h>

#include<iostream.h>

class distance

{

private:

int feet;

float inches;

public:

distance():feet(0),inches(0.0) //constructor with no args

{}

distance(int ft,float in):feet(ft),inches(in) //constructor with two args

{}

friend istream& operator >>(istream& s,distance& d);

friend ostream& operator <<(ostream& s,distance& d);

};


istream& operator >> (istream& s,distance& d) //get data from file or keyboard

{

char ch;

s>>d.feet>>ch>>ch>>d.inches>>ch;   //overload >> operator

return s;

}


ostream& operator << (ostream& s,distance& d) //send data to file or screen

{

s<<d.feet<<"\'-"<<d.inches<<'\"'; //overload << operator

return s;

}


void main()

{

char c;

distance d1;

ofstream ofile;      //create and open output stream

clrscr();

ofile.open("dist.dat");

do

{

cout<<"\nEnter distance :";

cin>>d1;                     //get distance from user

ofile<<d1;                  //write it to output stream

cout<<"\nWant to enter more details (y/n)?";

cin>>c;

}while(c!='n'); 

ofile.close();             //close output stream


ifstream ifile;             //create and open input stream

ifile.open("dist.dat");

cout<<"\nContents of file are :\n";

while(1)

{

ifile>>d1;               //read distance from stream

if(ifile.eof())            //quit on EOf

break;

cout<<"Distance :"<<d1<<endl;       //display distance

}

getch();

}

*** PLEASE checkout the Best deals from for top sites like Amazon, Flipkart etc ***