文件流-ASCII文件(中北大学-程序设计基础(2))

目录

题目

源码

结果示例


题目

编写程序实现以下功能:【要求处理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;
}

结果示例

  • 12
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Li-Shan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值