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 
#include 
#include 
#include 

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.
";
 exit(EXIT_FAILURE);
 }

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

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

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

 Employee emp2;

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

 cout << emp2;
}

 

Discussion

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

Numbers

Strings and Text

Dates and Times

Managing Data with Containers

Algorithms

Classes

Exceptions and Safety

Streams and Files

Science and Mathematics

Multithreading

Internationalization

XML

Miscellaneous

Index



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

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net