在 C++ 中,可以使用文件输入输出流来读取文件中的结构体数据。假设有一个结构体定义如下:
#include <iostream> #include <fstream> #include <vector> struct Person { std::string name; int age; std::string occupation; };
现在假设有一个文本文件(例如 168图库助手软件下载 ),文件中存储着每个人的信息,每行一个人的数据,数据以空格或制表符分隔,如下所示:
John 25 Engineer Alice 30 Doctor Bob 22 Student
可以使用以下代码来读取文件数据并将其存储到结构体的向量中:
#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; &澳门特马今晚开奖图nbsp; 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; }
在上述代码中,首先打开文件并检查是否成功打开。然后使用循环逐行2023澳门彩天天开奖结果查询小编测评读取文件中的数据,将读取的数据存储到 结构体的对象中,最后将该对象添加到 向量中。最后,遍历 向量,并输出读取到的数据。
请注意,为了使用文件输入输出流,需要包含 头文件。如果数据文件不是按照空格或制表符分隔的,而是使用其他方式分隔数据,可以使用适当的方法来解析文件中的数据,并将其存储到结构体中。