实验八:文件处理

题目

五金店的老板,需要保持库存,可以告诉你你有什么不同的工具,你有多少的手,每一个的成本。
(a)编写一个程序,初始化顺序文件hardware.txt,关于每个工具允许您输入的数据,允许您列出所有工具,允许您删除不再拥有的工具的记录,并允许您更新文件中的任何信息。工具识别号应为记录号。使用以下信息启动文件:
在这里插入图片描述
(b)重复(a),但这次使用的是随机访问文件hardware.dat。您应该为上述记录创建一个类,并为每条记录创建一个对象。在创建随机访问文件时,需要创建100条空记录。

代码

// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
class tool {
public:
    int record;
    string name;
    int quantity;
    double cost;
};
class record
{
public:
    record() { data.resize(100); };
    ~record() {};
    bool readdata(string path) {
        ifstream ifs(path);
        if (!ifs.is_open())
        {
            return false;
        }
        string temp;
        int idx=0;
        while (getline(ifs, temp,' '))
        {
            data[idx].record = stoi(temp);
            getline(ifs, temp, ' ');
            data[idx].name = temp;
            getline(ifs, temp, ' ');
            data[idx].quantity = stoi(temp);
            getline(ifs, temp);
            data[idx].cost = stof(temp);
        }
        ifs.close();
        return true;
    }
private:
    vector<tool> data;
};


int main()
{
    ofstream ofs;
    int tmp_i;
    string tmp_s;
    double tmp_f;
    ofs.open("hardware.txt", ios::out);
    while (1) {

        cout << "input a tool" << endl;
        cout << "record id?";
        cin >> tmp_i;
        ofs << tmp_i << " ";

        cout << "record name?";
        getline(cin, tmp_s);
        getline(cin, tmp_s);
        ofs << tmp_s << " ";

        cout << "record quntity?";
        cin >> tmp_i;
        ofs << tmp_i << " ";

        cout << "cost?";
        cin >> tmp_f;
        ofs << tmp_f <<endl;//<< ","

        cout << "continue?";
        cin >> tmp_i;
        if (tmp_i == 0) {
            break;
        }

    }
    ofs.close();
   
    record r;
    r.readdata("hardware.txt");

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

清欢_小铭

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

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

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

打赏作者

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

抵扣说明:

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

余额充值