C++编程实现以下功能: 1、定义职工类employee:字段成员:职工号num,姓名name,年龄age,工资salary; 成员函数:返回职工号getnum();友元函数:重载运算符>>,<<。 2、编写函数按职工号从小到大的顺序将 5 个职工的数据输出到磁盘文件 file1.txt中保存,int savetofile();该函数返回输入数据的个数。 3、编写函数从键盘输入一个员工的数据,增加到文件file1.txt 的末尾,int insertfile(int n);插入完成后将新的员工的数量返回。 4、编写函数从文件中输出全部员工的数据,void outfromfile(int n)。 5、编写函数从键盘输入一个号码,从文件中查找有无此职工号,如有则显示此职工是第几个职工以及此职工的全部数据,如没有,输出“无此人”,void findfile(int n)。
时间: 2024-02-03 17:13:03 浏览: 72
以下是实现以上功能的代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
class employee {
private:
int num;
string name;
int age;
int salary;
public:
employee(int n = 0, string nm = "", int a = 0, int s = 0) : num(n), name(nm), age(a), salary(s) {}
int getnum() const {
return num;
}
friend istream& operator>>(istream& is, employee& e) {
is >> e.num >> e.name >> e.age >> e.salary;
return is;
}
friend ostream& operator<<(ostream& os, const employee& e) {
os << e.num << "\t" << e.name << "\t" << e.age << "\t" << e.salary << endl;
return os;
}
bool operator<(const employee& e) const {
return num < e.num;
}
};
int savetofile(employee arr[], int n) {
sort(arr, arr+n); // 按职工号从小到大排序
ofstream ofs("file1.txt");
if (!ofs) {
cerr << "Failed to open file1.txt" << endl;
return 0;
}
for (int i = 0; i < n; i++) {
ofs << arr[i];
}
ofs.close();
return n;
}
int insertfile() {
ifstream ifs("file1.txt");
if (!ifs) {
cerr << "Failed to open file1.txt" << endl;
return 0;
}
int n = 0;
employee e;
while (ifs >> e) {
n++;
}
ifs.close();
ofstream ofs("file1.txt", ios::app);
if (!ofs) {
cerr << "Failed to open file1.txt" << endl;
return 0;
}
cout << "Enter data for the new employee (num name age salary): ";
cin >> e;
ofs << e;
ofs.close();
return n+1;
}
void outfromfile(int n) {
ifstream ifs("file1.txt");
if (!ifs) {
cerr << "Failed to open file1.txt" << endl;
return;
}
employee e;
for (int i = 0; i < n; i++) {
if (!(ifs >> e)) {
cerr << "Failed to read from file1.txt" << endl;
ifs.close();
return;
}
cout << e;
}
ifs.close();
}
void findfile(int n) {
ifstream ifs("file1.txt");
if (!ifs) {
cerr << "Failed to open file1.txt" << endl;
return;
}
employee e;
int i = 0;
while (ifs >> e) {
i++;
if (e.getnum() == n) {
cout << "This employee is the " << i << "th employee." << endl;
cout << e;
ifs.close();
return;
}
}
cout << "No such employee." << endl;
ifs.close();
}
int main() {
employee arr[5] = {
employee(2, "Tom", 25, 3500),
employee(3, "Jerry", 30, 4500),
employee(1, "Alice", 20, 2500),
employee(4, "Bob", 35, 5500),
employee(5, "David", 40, 6500)
};
int n = savetofile(arr, 5);
cout << "Saved " << n << " employees to file1.txt" << endl;
n = insertfile();
cout << "Inserted a new employee. Now there are " << n << " employees in file1.txt" << endl;
cout << "All employees in file1.txt: " << endl;
outfromfile(n);
int num;
cout << "Enter a number to search: ";
cin >> num;
findfile(num);
return 0;
}
```
这里使用了文件流来读写文件,并且重载了运算符>>和<<来方便地输入输出职工数据。插入新员工时使用了文件流的ios::app模式来在文件末尾添加数据。
阅读全文