10.5. Making a Class Readable from a Stream

Problem

You have written an object of some class to a stream, and now you need to read that data from the stream and use it to initialize an object of the same class.

Solution

Use operator>> to read data from the stream into your class to populate its data members, which is simply the reverse of what Example 10-6 does. See Example 10-7 for an implementation.

Example 10-7. Reading data into an object from a stream

#include <iostream> #include <istream> #include <fstream> #include <string> using namespace std; class Employee { friend ostream& operator<< // These have to be friends (ostream& out, const Employee& emp); // so they can access friend istream& operator>> // nonpublic members (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_; }; // Send an Employee object to an ostream... ostream& operator<<(ostream& out, const Employee& emp) { out << emp.firstName_ << endl; out << emp.lastName_ << endl; return(out); } // Read an Employee object from a stream istream& operator>>(istream& in, Employee& emp) { in >> emp.firstName_; in >> emp.lastName_; return(in); } int main() { Employee emp; string first = "William"; string last = "Shatner"; emp.setFirstName(first); emp.setLastName(last); ofstream out("tmp\\emp.txt"); if (!out) { cerr << "Unable to open output file.\n"; exit(EXIT_FAILURE); ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.