题目
五金店的老板,需要保持库存,可以告诉你你有什么不同的工具,你有多少的手,每一个的成本。
(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");
}