Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page