Making a Class Readable from a Stream


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.


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


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);

 Employee( ) {}
 ~Employee( ) {}

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

 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;


// Read an Employee object from a stream
istream& operator>>(istream& in, Employee& emp) {

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


int main( ) {

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


 ofstream out("tmp\emp.txt");

 if (!out) {
 cerr << "Unable to open output file.

 out << emp; // Write the Emp to the file
 out.close( );

 ifstream in("tmp\emp.txt");

 if (!in) {
 cerr << "Unable to open input file.

 Employee emp2;

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

 cout << emp2;



The steps for making a class readable from a stream are nearly identical to, but the opposite of, those for writing an object to a stream. If you have not already read Recipe 10.4, you should do so for Example 10-7 to make sense.

First, you have to declare an operator>> as a friend of your target class, but, in this case, you want it to use an istream instead of an ostream. Then define operator>> (instead of operator<<) to read values from the stream directly into each of your class's member variables. When you are done reading in data, return the input stream.

See Also

Recipe 10.4

Building C++ Applications

Code Organization


Strings and Text

Dates and Times

Managing Data with Containers



Exceptions and Safety

Streams and Files

Science and Mathematics






C++ Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2006
Pages: 241

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: