iostream迭代器的使用

来源:互联网 发布:沁人缘淘宝网 编辑:程序博客网 时间:2024/04/30 00:17
01#include<iostream>
02#include<fstream>
03#include<string>
04#include<iterator>
05#include<cstdlib>
06using namespace std;
07 
08ofstream & openFile(ofstream &out,const string &fileName)
09{
10    out.close();
11    out.clear();
12    out.open(fileName.c_str());
13    return out;
14}
15 
16ifstream & openFile(ifstream &in,const string &fileName)
17{
18    in.close();
19    in.clear();
20    in.open(fileName.c_str());
21    return in;
22}
23 
24int main()
25{
26    cout<<"Enter two file name:"<<endl;
27    string filename1,filename2;
28    cin>>filename1>>filename2;
29 
30    ofstream outfile1,outfile2;
31    openFile(outfile1,filename1);
32    openFile(outfile2,filename2);
33 
34    cout<<"Enter some integers:"<<endl;
35    istream_iterator<int> input(cin),eof;
36    ostream_iterator<int> output1(outfile1," ");
37    ostream_iterator<int> output2(outfile2,"\n");
38     
39    while(input!=eof)
40    {
41        if(*input%2)
42            *output1++=*input++;
43        else
44            *output2++=*input++;
45    }
46    outfile1.close();
47    outfile2.close(); //close file
48 
49 
50    cout<<"odd number contains:"<<endl;
51    ifstream infile;
52    openFile(infile,filename1);
53    istream_iterator<int> in(infile),end_of_stream;
54    ostream_iterator<int> out(cout," ");
55    while(in!=end_of_stream)
56        *out++=*in++;
57    cout<<endl;
58 
59    return 0;
60}


转自:http://my.oschina.net/ppppower/blog/37274
原创粉丝点击