C++ 从格式化的文本文件中读取“ struct”。
示例
C ++ 11struct 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 Wabbit2
6.2
Bilbo Baggins
111
81.3
Mary Poppins
29
154.8
输出:
name: Wogger Wabbitage: 2 years
height: 6.2lbs
name: Bilbo Baggins
age: 111 years
height: 81.3lbs
name: Mary Poppins
age: 29 years
height: 154.8lbs
以上是 C++ 从格式化的文本文件中读取“ struct”。 的全部内容, 来源链接: utcz.com/z/330700.html