本文已参与「新人创作礼」活动,一起开启掘金创作之路。
题目
五金店的老板,需要保持库存,可以告诉你你有什么不同的工具,你有多少的手,每一个的成本。
(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); };//构造函数,将数据data初始化为固定大小
~record() {};//析构函数
bool readdata(string path) {//根据函数参数读取文件,返回是否读取成功
ifstream ifs(path);//文件输入流(input file stream)
if (!ifs.is_open())
{
return false;//文件打开错误,一般是不存在
}
string temp;
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);
idx++;//指向下一个
}
ifs.close();//关闭文件
return true;
}
private:
int idx=0;//数据尾部指针
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");
}