Use istream_iterator and ostream_iterator to read from cin and write to cout. : istream_iterator « File Stream « C++ Tutorial






#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;

int main()
{
  unsigned i;
  double d;
  string str;
  vector<int> vi;
  vector<double> vd;
  vector<string> vs;

  cout << "Enter some integers, enter 0 to stop.\n";
  istream_iterator<int> int_itr(cin);
  do {
    i = *int_itr; 
    if(i != 0) {
      vi.push_back(i); 
      ++int_itr; 
    }
  } while (i != 0);

  cout << "Enter some doubles, enter 0 to stop.\n";
  istream_iterator<double> double_itr(cin);
  do {
    d = *double_itr;
    if(d != 0.0) {
      vd.push_back(d); 
      ++double_itr; 
    }
  } while (d != 0.0);

  cout << "Enter some strings, enter 'quit' to stop.\n";
  istream_iterator<string> string_itr(cin);
  do {
    str = *string_itr; 
    if(str != "quit") {
      vs.push_back(str);
      ++string_itr;
    }
  } while (str != "quit");

  cout << endl;

  cout << "Here is what you entered:\n";
  for(i=0; i < vi.size(); i++) cout << vi[i] << " ";
  cout << endl;

  for(i=0; i < vd.size(); i++) cout << vd[i] << " ";
  cout << endl;

  for(i=0; i < vs.size(); i++) cout << vs[i] << " ";


  // Now, use ostream_iterator to write to cout.

  // Create an output iterator for string.
  ostream_iterator<string> out_string_itr(cout);
  *out_string_itr = "\n";
  *out_string_itr = string("\nThis is a string\n");
  *out_string_itr = "This is too.\n";

  // Create an output iterator for int.
  ostream_iterator<int> out_int_itr(cout);
  *out_int_itr = 10;
  *out_string_itr = " ";
  *out_int_itr = 15;
  *out_string_itr = " ";
  *out_int_itr = 20;

  *out_string_itr = "\n";

  // Create an output iterator for bool.
  ostream_iterator<bool> out_bool_itr(cout);
  *out_bool_itr = true;
  *out_string_itr = " ";
  *out_bool_itr = false;

  return 0;
}








12.14.istream_iterator
12.14.1.Use istream_iterator
12.14.2.Create istream_iterator for reading int values from cin
12.14.3.Use istream_iterator and ostream_iterator to read from cin and write to cout.
12.14.4.Use istreambuf_iterator, ostreambuf_iterator, and replace_copy() to filter a file.