目录
题目
源码
结果示例
题目
编写程序实现以下功能:【要求处理ASCII文件】
(1)按职工号由小到大的顺序将5个员工的数据(包括号码、姓名、年龄和工资)输出到磁盘文件中保存;
(2)从键盘输入两个员工的数据(职工号大于已有的职工号),增加到文件末尾;
(3)输出文件中全部职工的数据;
(4)从键盘输入一个号码,从文件中查找有无此职工号,如有则显示此职工是第几个职工以及此职工的全部数据。如没有,输出“无此人”。可以反复多次查询,如果输入查找的职工号为0,就结束查询。
源码
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Employee
{
public:
int id;
string name;
int age;
double salary;
Employee() {}
Employee(int i, string n, int a, double s) : id(i), name(n), age(a), salary(s) {}
void output(ofstream &file)
{
file << "号码: " << id << ", 姓名: " << name << ", 年龄: " << age << ", 工资: " << salary << endl;
}
};
int main()
{
ofstream file("employee_data.txt", ios::app);
// (1) 输出5个员工的数据到文件
Employee employees[7] = {
{101, "qqq", 25, 5000},
{102, "www", 30, 6000},
{103, "eee", 28, 5500},
{104, "rrr", 35, 7000},
{105, "ttt", 27, 5200}};
for (int i = 0; i < 5; i++)
{
employees[i].output(file);
}
// (2) 从键盘输入两个员工的数据,增加到文件末尾
for (int i = 5; i < 7; i++)
{
cout << "请输入员工号码: ";
cin >> employees[i].id;
cout << "请输入员工姓名: ";
cin >> employees[i].name;
cout << "请输入员工年龄: ";
cin >> employees[i].age;
cout << "请输入员工工资: ";
cin >> employees[i].salary;
employees[i].output(file);
}
file.close();
// (3) 输出文件中全部职工的数据
ifstream inFile("employee_data.txt");
string line;
while (getline(inFile, line))
{
cout << line << endl;
}
inFile.close();
// (4) 从文件中查找职工号
int searchId;
while (true)
{
cout << "输入员工号码查找员工 (输入0以结束): ";
cin >> searchId;
if (searchId == 0)
{
break;
}
ifstream inFile("employee_data.txt");
bool found = false;
int count = 0;
while (getline(inFile, line))
{
count++;
if (line.find("号码: " + to_string(searchId)) != string::npos)
{
found = true;
cout << "此职工是第" << count << "个员工: " << line << endl;
break;
}
}
inFile.close();
if (!found)
{
cout << "未找到职工" << endl;
}
}
return 0;
}