Making a Class Readable from a Stream - C++ Class

C++ examples for Class:Operator Overload

Description

Making a Class Readable from a Stream

Demo Code

#include <iostream>
#include <istream>
#include <fstream>
#include <string>

using namespace std;

class Employee {//from w w w .  j  ava 2  s. co m
   friend ostream& operator<< (ostream& out, const Employee& emp);
   friend istream& operator>> (istream& in, Employee& emp);

public:
   Employee() {}
  ~Employee() {}

   void setFirstName(const string& name) {firstName_ = name;}
   void setLastName(const string& name) {lastName_ = name;}

private:
   string firstName_;
   string lastName_;
};

ostream& operator<<(ostream& out, const Employee& emp) {
   out << emp.firstName_ << endl;
   out << emp.lastName_ << endl;

   return(out);
}

istream& operator>>(istream& in, Employee& emp) {

   in >> emp.firstName_;
   in >> emp.lastName_;

   return(in);
}

int main() {

   Employee emp;
   string first = "first";
   string last = "last";

   emp.setFirstName(first);
   emp.setLastName(last);

   ofstream out("emp.txt");

   if (!out) {
      cerr << "Unable to open output file.\n";
      exit(EXIT_FAILURE);
   }
   out << emp;
   out.close();

   ifstream in("emp.txt");

   if (!in) {
      cerr << "Unable to open input file.\n";
      exit(EXIT_FAILURE);
   }

   Employee emp2;

   in >> emp2;  // Read the file into an empty object
   in.close();

   cout << emp2;
}

Result


Related Tutorials