Home arrow C++ arrow Page 4 - Manipulating Streams and Files with C++
C++

Manipulating Streams and Files with C++


In this second part of a five-part series on handling streams and files in C++, you will learn how to format floating-point output, how to write your own stream manipulators, and more. This article is excerpted from chapter 10 of the C++ Cookbook, written by Ryan Stephens, Christopher Diggins, Jonathan Turkanis and Jeff Cogswell (O'Reilly; ISBN: 0596007612). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 5 stars5 stars5 stars5 stars5 stars / 1
October 23, 2008
TABLE OF CONTENTS:
  1. · Manipulating Streams and Files with C++
  2. · 10.3 Writing Your Own Stream Manipulators
  3. · 10.4 Making a Class Writable to a Stream
  4. · 10.5 Making a Class Readable from a Stream

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

advertisement
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

#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);
  
}
  
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.

blog comments powered by Disqus
C++ ARTICLES

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 3 - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials