运行代码:
//向量与流迭代器
#include"std_lib_facilities.h"
struct Item
{
string name;
int iid;
double value;
friend istream& operator>>(istream& is, Item& ii);
friend ostream& operator<<(ostream& os, const Item& ii);
};
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());
istream_iterator<Item>ii(is);
istream_iterator<Item>eos;
ostream_iterator<Item>oo(cout, "\n");
vector<Item>vi(ii, eos);
copy(vi.begin(), vi.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
运行结果: