Description: D:\website\syllabus\study_matreials\c++\logo_pic\logo.jpg

Overloading << and >> with file stream



#include <iostream>
#include <fstream>
using namespace std;
#include "stdio.h"
class Complex
{
    int real;
    int img;
    public:
        Complex()
        {
                real =10;
                img = 50;
        }
        ~Complex()
        {
        }
        friend ostream& operator << (ostream& s, Complex& c);  //This is needed as the fun uses private data os Complex class
        friend istream& operator >> (istream& s, Complex& c);
        void Readfile();
        void Writefile();
};

void Complex::Readfile()
{
        fstream fstr;
        fstr.open("sample.txt", ios::in);
        string str;
        fstr>>str;
        cout<<str;
        fstr.close();
}
void Complex::Writefile()
{
        fstream fstr;
        fstr.open("sample.txt", ios::out);
        fstr<<"Kalyan";
        fstr<<*this;
        fstr.close();
}
        ostream& operator << (ostream& s, Complex& c)
        {
            printf("Inside overloaded << operator\n");
            s<<c.real<<"+i"<<c.img<<endl;
            return s;
        }
        istream& operator >>  (istream& s, Complex& c)
        {
            printf("Inside overloaded >> operator\n");
            printf("Enter real and img number: \n");
            s>>c.real>>c.img;
            return s;
        }
int main(){
    Complex c;
    c.Writefile();
    c.Readfile(); //outout:  Kalyan10+i50
    return 0;

}
 


Run in MyWhiteBoard


 

 

Copyright © Open Sky Technology