在C++中,可以使用文件输入输出流来将数据从文件读取到结构体中。假设有一个结构体定义如下:
#include <iostream> #include <fstream> #include <vector> struct Person { std::string name; int age; std::string occupation; };
现在假设有一个文本文件(例如),文件中存储着每个人的信息,每行一个人的数据,数据以空格或制表符分隔,如下所示:
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; } std::string name, occupation; int age; while (inputFile >> name >> age >> occupation) { Person person; person.name = name; person.age = age; person.occupation = 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; }
在上述代码中,首先打开文件并检查是否成功打开。然后使用循环逐行读取文件中的数据,将读取的数据存储到 管家婆2025年资料来源 结构体的对象中,最后将该对象添加到 向量中。最后,遍历 向量,并输出读取到的数据。
注意:为了使用文件输入输出流,需要包含 头文件。