c++读入文件创建对象
时间: 2024-05-25 22:08:57 浏览: 16
在C++中读取文件并创建对象,可以通过以下步骤实现:
1. 首先,需要定义一个类来表示文件中的数据。
2. 接着,定义一个函数,用于从文件中读取数据并创建对象。
3. 在函数中,需要打开文件并逐行读取数据。
4. 对于每一行数据,需要解析出各个字段,并使用这些字段创建一个对象。
5. 最后,将创建好的对象添加到一个数组或其他数据结构中,以便后续使用。
以下是一个简单的示例代码,仅供参考:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class Person {
public:
string name;
int age;
string gender;
Person(string n, int a, string g) {
name = n;
age = a;
gender = g;
}
};
vector<Person> readFromFile(string filename) {
vector<Person> people;
ifstream inFile(filename);
if (!inFile) {
cout << "Unable to open file";
exit(1);
}
string line;
while (getline(inFile, line)) {
string name;
int age;
string gender;
// 解析每一行数据,获取各个字段
// 假设文件格式为:name,age,gender
size_t pos = 0;
string token;
pos = line.find(",");
name = line.substr(0, pos);
line.erase(0, pos + 1);
pos = line.find(",");
age = stoi(line.substr(0, pos));
line.erase(0, pos + 1);
gender = line;
// 创建一个Person对象,并将其添加到people数组中
Person p(name, age, gender);
people.push_back(p);
}
inFile.close();
return people;
}
int main() {
vector<Person> people = readFromFile("data.txt");
for (auto p : people) {
cout << p.name << " " << p.age << " " << p.gender << endl;
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)