C++ STL stream iterator program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the stream iterator in C++ programming  to read from standard input and write to the standard output

To show: How to read from standard input and write to the standard output using the stream iterator in C++ programming

 

// C++ STL stream iterator

#include <iostream>

#include <vector>

#include <string>

#include <algorithm>

using namespace std;

 

int main(void)

{

// vector container

vector<string> strvec;

// container iterator

vector <string>::iterator Iter;

 

// read from the standard input until EOF/error

// the EOF is platform dependent...

// then copy (inserting) to strvec vector...

// copy from begin to end of source, to destination

cout<<"Enter some string (EOF) to terminate: "<<endl;

copy(istream_iterator<string>(cin), istream_iterator<string>(), back_inserter(strvec));

 

// print the result

cout<<"\nstrvec vector data: ";

for(Iter = strvec.begin(); Iter != strvec.end(); Iter++)

cout<<*Iter<<" ";

cout<<endl;

 

// do some sorting

sort(strvec.begin(), strvec.end());

 

// print the result

cout<<"\nstrvec vector data: ";

for(Iter = strvec.begin(); Iter != strvec.end(); Iter++)

cout<<*Iter<<" ";

cout<<endl<<endl;

 

// print all elements without duplicates to standard output

unique_copy(strvec.begin(), strvec.end(), ostream_iterator<string> (cout, "\n"));

return 0;

}

 

Output examples:

 

Enter some string (EOF) to terminate:

This is a line of text

Another line of text

^Z

strvec vector data: This is a line of text Another line of text

strvec vector data: Another This a is line line of of text text

Another

This

a

is

line

of

text

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index