首页 > 代码库 > ostream_iterator和istream_iterator使用杂谈

ostream_iterator和istream_iterator使用杂谈

我们在写Console程序时cout/cin,STL中提供了对应的iterator,可以更加灵活的使用。

 

 ostream_iterator<string> oo(cout);

 *oo="China\n";

 ++oo;

 *oo="English\n";

增加了类型的检查,*oo赋值为整形vs会报错。

// *oo=1; error

 

ostream_iterator可以做为函数对象放到copy中,这样可以输出s的每个值。

 string s="1234567890";

 copy(s.begin(),s.end(),ostream_iterator<char>(cout,"\t"));

 

结果如下:

 

 

同样的istream_iterator也可以声明对象。

 istream_iterator<int> intvecRead (cin);

 int temp=*intvecRead;

 cin.clear ( );

 

Ofstream可以输出到文件,代码如下。

ofstream ofs("11.txt");

 if (!ofs.bad())

 {

  string sf;

  cin>>sf;

  ofs << sf << endl;

  ofs.close();

 }

ifstream 读出写入的数据

ifstream ifs("11.txt");

 while (ifs!=NULL)

 {

  char str[10];

  ifs>>str;

  cout<<str<<endl;

 }

ostream_iterator和istream_iterator使用杂谈