Using istream_iterator and ostream_iterator to read from cin and write to cout. - C++ STL

C++ examples for STL:istream_iterator

Description

Using istream_iterator and ostream_iterator to read from cin and write to cout.

Demo Code

#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;
int main()/*from   w w  w . j ava2s  .c o m*/
{
   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; // read next int
      if(i != 0) {
         vi.push_back(i); // store it
         ++int_itr; // input next int
      }
   } while (i != 0);


   cout << "Enter some doubles, enter 0 to stop.\n";
   istream_iterator<double> double_itr(cin);
   do {
      d = *double_itr; // read next double
      if(d != 0.0) {
         vd.push_back(d); // store it
         ++double_itr; // input next double
      }
   } while (d != 0.0);
   // Create an input stream iterator for string.
   cout << "Enter some strings, enter 'quit' to stop.\n";
   istream_iterator<string> string_itr(cin);
   do {
      str = *string_itr; // read next string
      if(str != "quit") {
         vs.push_back(str); // store it
         ++string_itr;
      }
   } while (str != "quit"); // input next string
   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;
}

Result


Related Tutorials