Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

7.11. Printing a Range to a Stream

Problem

You have a range of elements that you want to print to a stream, most likely cout for debugging.

Solution

Write a function template that takes a range or a container, iterates through each element, and uses the copy algorithm and an ostream_iterator to write each element to a stream. If you want more control over formatting, write your own simple algorithm that iterates through a range and prints each element to the stream. (See Example 7-11.)

Example 7-11. Printing a range to a stream

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>

using namespace std;

int main() {

   // An input iterator is the opposite of an output iterator: it
   // reads elements from a stream as if it were a container.
   cout << "Enter a series of strings: ";
   istream_iterator<string> start(cin);
   istream_iterator<string> end;
   vector<string> v(start, end);

   // Treat the output stream as a container by using an
   // output_iterator.  It constructs an output iterator where writing
   // to each element is equivalent to writing it to the stream.
   copy(v.begin(), v.end(), ostream_iterator<string>(cout, ", "));
}

The output for Example 7-11 might look like this:

Enter a series of strings: z x y a b c
^Z
z, x, y, a, b, c,

Discussion

A stream iterator is an iterator that is based on a stream instead of a range of elements in some container, and stream iterators allow you to treat stream input as an input iterator (read from the dereferenced value ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page