运行代码:
//list与流迭代器
#include"std_lib_facilities.h"
//声明Item类
struct Item
{
string name;
int iid;
double value;
Item():name(" "),iid(0),value(0.0){}
Item(string ss,int ii,double vv):name(ss),iid(ii),value(vv){}
friend istream& operator>>(istream& is, Item& ii);
friend ostream& operator<<(ostream& os, const Item& ii);
};
//------------------------------------------------------------
//重载Item类的输入和输出操作符
istream& operator>>(istream& is, Item& ii)
{
is >> ii.name >> ii.iid >> ii.value;
return is;
}
ostream& operator<<(ostream& os, const Item& ii)
{
os << ii.name << " " << ii.iid << " " << ii.value;
return os;
}
//----------------------------------------------------------
int main()
try
{
cout << "输入读取文件名: ";
string from_file;
cin >> from_file;
ifstream is(from_file.c_str());
if (!is)error("can't open ", from_file);
istream_iterator<Item>ii(is);
istream_iterator<Item>eos;
ostream_iterator<Item>oo(cout, "\n");
list<Item>ll(ii, eos);
copy(ll.begin(), ll.end(), oo);
return 0;
}
catch (exception& e) {
cerr << "error:" << e.what() << '\n';
keep_window_open();
return 1;
}
catch (...) {
cerr << "Oops:unknown exception!\n";
keep_window_open();
return 2;
}
读取文件:Item_file.txt
Max 2 43.2
Jane 3 34.2
Tom 3 32.4
Mary 8 23.0
Peter 5 32.5
Max 2 43.2
Jane 3 34.2
Tom 3 32.4
Mary 8 23.0
Peter 5 32.5
运行结果:文章来源:https://www.toymoban.com/news/detail-619689.html
文章来源地址https://www.toymoban.com/news/detail-619689.html
到了这里,关于list与流迭代器stream_iterator的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!