Home > Articles > Programming > C/C++

📄 Contents

  1. Using Manipulators To Control Object Format
  2. Connecting Algorithms and Containers to Streams
  3. Summary
  • Print
  • + Share This
Like this article? We recommend

Connecting Algorithms and Containers to Streams

To illustrate how all of this works in C++, we'll use our course class and Schedule container from part 1 and part 2 of this series. We want our course class to be iostream compatible. Keep in mind that the built-in types can be streamed with different formatting depending on the application. For instance, a float can be formatted in the stream with fixed-point, scientific, or exponential notation, and can have a specified precision. An int can be formatted in the stream with hex, oct, or decimal format; a string can be formatted in the stream with left/right alignment, specified padding, and fill character. The user-defined classes should also come prepared. In our case, the course class has its native format. It can also be represented as HTML, XML, or horn clause. We also would like manipulators that can be used to specify the format our course class can take during insertion or extraction. We have several user-defined manipulators that apply to our course class:

  • XML

  • HTML

  • hornClause

  • militaryTime

  • clockTime

  • SSPR (short for simple sound phonetic representation)

Listing 1 shows an abbreviated declaration and definition for our course class, the definition of operators << and >>, manipulators, and our schedule of courses.

Listing 1 An abbreviated declaration and definition of the course class.

class course{ 
  string StartTime;
  string EndTime;
  string Days;
  string Description; 
  string startTime(void) const;
  string endTime(void) const;
  string days(void) const;
  string description(void) const;
  course &operator=(const course &Course);
  friend istream &operator>>(istream &In,course &Course);
  friend ostream &operator<<(ostream &Out,const course &Course);

// ...
// definition of operator<<()

ostream &operator<<(ostream &Out,const course &Course)
  if(Out.iword(UserFlag["LanguageBase"]) == XmlRep){
   Out << "<COURSE_START_TIME>"  << Course.startTime()  <<
       "</COURSE_START_TIME>" <<
       "<COURSE_END_TIME>"   << Course.endTime()   <<
       "</COURSE_END_TIME>"  <<
       "<COURSE_DESCRIPTION>" << Course.description() <<
       "<COURSE_DAYS>"     << Course.days() <<

     if(Out.iword(UserFlag["LanguageBase"]) == HtmlRep){
       Out << "<tr>"     << endl  <<
       "<td>Start Time</td>" << endl  <<
       "<td>"   << Course.startTime()
            << "</td></tr>"
            << endl  <<
       "<tr>"   << endl  <<
       "<td>End Time</td>"  << endl  <<
       "<td>"   << Course.endTime()
            << "</td></tr>"
            << endl  <<
       "<tr>"   << endl  <<
       "<td>Description</td>"<< endl  <<
       "<td>"   << Course.description()<<
       "</td></tr>"<< endl  <<
       "<tr>"   << endl  <<
       "<td>Days</td>" << endl <<
       "<td>"   << Course.days()
            << "</td></tr>" << endl;
     if(Out.iword(UserFlag["HornClause"]) == HClause){
       Out << Course.toHornClause()  // Horn Clause processing
     Out << Course.startTime() << endl
       << Course.endTime()  << endl
       << Course.description() << endl
       << Course.days()    << endl;

// definition of operator>>()
istream &operator>>(istream &In, course &Course)
   string X;
   int Pos;
   char Temp[80];

   Pos = X.find("COURSE");
   if(Pos != string::npos){





// manipulators

ostream &xml(ostream &SomeStream)
  if(UserFlag.find("LanguageBase") == UserFlag.end()){
    UserFlag["LanguageBase"] = SomeStream.xalloc();
   SomeStream.iword(UserFlag["LanguageBase"]) = XmlRep;

ostream &html(ostream &SomeStream)
  if(UserFlag.find("LanguageBase") == UserFlag.end()){
    UserFlag["LanguageBase"] = SomeStream.xalloc();
   SomeStream.iword(UserFlag["LanguageBase"]) = HtmlRep;

ostream &hornClause(ostream &SomeStream)
  if(UserFlag.find("LanguageBase") == UserFlag.end()){
    UserFlag["LanguageBase"] = SomeStream.xalloc();
   SomeStream.iword(UserFlag["LanguageBase"]) = HClause;

// declaration of schedule of courses

vector<course> Schedule;

We want to send our schedule of courses to a printer. Rather than send the courses in their native format, we would like to insert the courses as XML into the printer stream. We'll avoid using the traditional print loop and save coding effort by using the STL copy() algorithm instead. Listing 2 shows how this is set up using an ostream_iterator and the Schedule container.

Listing 2 Using the copy algorithm and iterators to read and print a container of course objects.

int main(int argc,char *argv[])
  ifstream Input(open("courses.dat"));
  vector<course> Schedule;
  istream_iterator<course> In(Input);
  istream_iterator<course> eof;



  ofstream DegreePlan(open("/dev/lp0",O_WRONLY));


  DegreePlan << xml;
  ostream_iterator<course> Out(DegreePlan,"\n");



In Listing 2, the contents for the course objects are stored in the courses.dat file in XML format. The copy algorithm uses the istream_iterator that in turn utilizes the >> operator of the course object. Listing 1 shows the definition of the extractor. The copy algorithm assigns the content of the course objects to the vector of courses. Once the vector is populated with course objects, they can be sent to the printer. The XML manipulator is inserted into the stream prior to calling the copy() algorithm again. This is necessary because we want the format state of the stream to be set before the copy() algorithm starts its work. This design will ensure that the proper stream state is visible to the << operator. This time, the copy() algorithm uses the ostream_iterator to visit each course object in the vector. The ostream_iterator will use the operator << to insert the courses into the printer stream. The operator << assumes that the stream format state has already been set. (Therefore, set any stream formatting flags or manipulators prior to applying any algorithm.) The format the course will take in the stream is determined in the definition of the << operator. Listing 3 contains a simple implementation of an ostream_iterator:

Listing 3 A simple implementation of an ostream iterator.

template <class _Tp>
class ostream_iterator {
protected:  ostream* _M_stream;
  const char* _M_string;
  ostream_iterator(ostream& __s):_M_stream(&__s),_M_string(0) {}
  ostream_iterator(ostream& __s,const char* __c):_M_stream(&__s), _M_string(__c) {}
  ostream_iterator<_Tp>& operator=(const _Tp& __value){
   *_M_stream << __value;
   if (_M_string) *_M_stream << _M_string;
   return *this;
  ostream_iterator<_Tp>& operator*() { return *this; }
  ostream_iterator<_Tp>& operator++() { return *this; }
  ostream_iterator<_Tp>& operator++(int) { return *this; }

Data members are protected here (class from STL)

Notice in Listing 3 that the ostream_iterator will invoke the << operator on the object that it's inserting into the stream. This is one of the primary connections between the iostreams and the STL containers and algorithms. The ostream_iterator or istream_iterator is connected to a stream. The algorithms can use the ostream and istream iterators to access objects in STL containers. The objects in the containers have the operator << or >> defined. Figure 3 illustrates how the stream iterators form the bridge between the algorithms, containers, and the iostreams.

Figure 3Figure 3 Stream iterators are used to connect algorithms, containers, and iostreams.

In Figure 3, the algorithms connect to the containers through stream iterators. The stream iterators in turn invoke stream inserters or extractors, and the inserters and extractors do the stream processing. In this case, the copy() algorithm copies our course objects to a printer properly formatted as XML.

The ability to connect algorithms and containers to streams opens a world of interesting possibilities because we can connect streams to all sorts of devices: cable modems, network cards, printers, PDAs, scanners, sound cards, and so on. For instance, the curriculum-planning software that we use at CTEST labs has a text-to-speech component. We routinely use the algorithms and containers connected to the iostreams for text-to-speech processing using a sound card. Connection to the sound card is accomplished by deriving new classes from streambuf and ostream. In our case, the streambuf class is perhaps the most important because this is where the connection is made to the sound card. In general, << and >> ultimately send and receive their bytes to a streambuf object or one of its descendants. The streambuf object performs the actual I/O. When a new I/O device needs to be addressed, the streambuf class and its derivative are usually the center of attention. Listing 4 shows a scaled-down version of our tts_buf class.

Listing 4 Scaled down version of the tts_buf class.

class tts_buf : public streambuf{
  synthesized_voice * Voice;
  std::streamsize xsputn(const char *s, std::streamsize num);


std::streamsize tts_buf::xsputn(const char *S, std::streamsize Num)
  string Expression(S,Num);



  Voice = new synthesized_voice;


  delete Voice;

To direct our output to a speech engine that will ultimately send it to the sound card, we override the xsputn() method of the streambuf class. Since we typically send character strings to the speech engine, we don't need to override xsputc(). xsputn() is the lowest-level method that deals with character streams, so we direct the output to the speech engine in this method. Once this is done, we can construct an ostream object with a tts_buf object. Any character strings inserted into this object will be spoken by the speech engine. Also, our user-defined inserter will format the character string appropriately (using the user-defined manipulators) before passing it to the tts_buf object. Listing 5 shows how the tts_buf object is used with an ostream object and how that object is then connected to an ostream_iterator.

Listing 5 Using the tts_buf object, ostream object, and an ostream iterator.

#include "course.h"
#include <iterator>
#include <algorithm>
#include <vector>

int main(int argc,char *argv[])

  course Course;
  course Course2;
  course Course3;
  vector<course> Schedule;

  tts_buf TTSBuf;
  ostream Speech(&TTSBuf);
  Speech << sspr;
  ostream_iterator<course> Out(Speech," ");


Notice in Listing 5 that the copy() algorithm is used to send the contents of the course schedule to the text-to-speech engine. This will cause the speech engine to pronounce the contents of each course object. The sspr (simple sound phonetic representation) is a user-defined manipulator that causes the inserter for the course object to output its start and end times—3:00, 4:00, 5:00—as "three o'clock," "four o'clock," and "five o'clock," respectively. A course with a start time of 12:00 would be pronounced "twelve o'clock."

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020