c++文件读入结构体
作者:野牛程序员:2023-07-31 20:49:14 C++阅读 2269
在 C++ 中,可以使用文件输入输出流来读取结构体数据。假设有一个结构体定义如下:
#include <iostream> #include <fstream> #include <vector> struct Person { std::string name; int age; std::string occupation; };
现在假设有一个文本文件(例如data.txt
),文件中存储着每个人的信息,每行一个人的数据,数据以空格或制表符分隔,如下所示:
John 25 Engineer Alice 30 Doctor Bob 22 Student
可以使用以下代码来读取文件数据并将其存储到结构体的 vector 中:
#include <iostream> #include <fstream> #include <vector> struct Person { std::string name; int age; std::string occupation; }; int main() { std::vector<Person> people; std::ifstream inputFile("data.txt"); if (!inputFile) { std::cerr << "Error opening file." << std::endl; return 1; } Person person; while (inputFile >> person.name >> person.age >> person.occupation) { people.push_back(person); } inputFile.close(); // 输出读取的数据 for (const auto& person : people) { std::cout << "Name: " << person.name << ", Age: " << person.age << ", Occupation: " << person.occupation << std::endl; } return 0; }
在上述代码中,首先打开文件并检查是否成功打开。然后使用循环逐行读取文件中的数据,将读取的数据存储到 Person
结构体的对象中,最后将该对象添加到 people
vector 中。最后,遍历 people
vector,并输出读取到的数据。
请注意,为了使用文件输入输出流,需要包含 <fstream>
头文件。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
- 上一篇:c语言遍历结构体
- 下一篇:c++读取文件中结构体