struct info_type { std::string name; int age; float height; // we define an overload of operator>> as a friend function which // 授予对私有数据成员的特权访问 friend std::istream& operator>>(std::istream& is, info_type& info) { // 跳过空格 is >> std::ws; std::getline(is, info.name); is >> info.age; is >> info.height; return is; } }; void func4() { auto file = std::ifstream("file4.txt"); std::vector<info_type> v; for(info_type info; file >> info;) // 继续阅读直到我们用完为止 { // 我们只有在读取成功的情况下才能到达这里 v.push_back(info); } for(auto const& info: v) { std::cout << " name: " <<info.name<< '\n'; std::cout << " age: " <<info.age<< " years" << '\n'; std::cout << "height: " <<info.height<< "lbs" << '\n'; std::cout << '\n'; } }
file4.txt
Wogger Wabbit 2 6.2 Bilbo Baggins 111 81.3 Mary Poppins 29 154.8
输出:
name: Wogger Wabbit age: 2 years height: 6.2lbs name: Bilbo Baggins age: 111 years height: 81.3lbs name: Mary Poppins age: 29 years height: 154.8lbs