那怎么实现每个员工都信息都能保存在各自独立的文件中呢
时间: 2024-02-27 09:56:36 浏览: 24
可以将每个员工的信息保存到一个独立的文件中,文件名可以使用员工的工号或其他唯一标识符。
在保存员工信息时,可以使用文件流将员工对象的属性逐一写入到文件中,例如:
```c++
// 假设员工对象的属性如下:
// string name; // 姓名
// int age; // 年龄
// string id; // 工号
// 将员工信息保存到文件中
void saveToFile() {
// 以员工的工号作为文件名
string filename = id + ".txt";
// 打开文件
ofstream ofs(filename);
// 写入员工信息
ofs << name << endl;
ofs << age << endl;
ofs << id << endl;
// 关闭文件
ofs.close();
}
```
在读取员工信息时,可以先获取所有员工的工号或文件名,然后逐一读取每个文件中的员工信息,例如:
```c++
// 读取所有员工的信息
void readAllEmployees() {
// 获取所有员工的工号或文件名
vector<string> ids = getAllEmployeeIds();
// 逐一读取每个文件中的员工信息
for (string id : ids) {
// 以员工的工号作为文件名
string filename = id + ".txt";
// 打开文件
ifstream ifs(filename);
// 读取员工信息
string name;
int age;
ifs >> name;
ifs >> age;
// 创建员工对象并加入到员工列表中
Employee employee(name, age, id);
employees.push_back(employee);
// 关闭文件
ifs.close();
}
}
```
其中,`getAllEmployeeIds`函数可以返回所有员工的工号或文件名,例如可以扫描员工信息存储目录下的所有文件,然后去掉文件扩展名得到员工的工号。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)