Manipulating Streams and Files with C++ - 10.5 Making a Class Readable from a Stream (Page 4 of 4 )
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
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);
// 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); } out << emp; // Write the Emp to the file out.close();
ifstream in("tmp\\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; }
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
Please check back next week for the continuation of this article.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.