C++ Primer(第5版) 练习 8.8
练习 8.8 修改上一题的程序,将结果追加到给定的文件末尾。对同一个输出文件,运行程序至少两次,检验数据是否得以保留。
环境:Linux Ubuntu(云服务器)
工具:vim
代码块
*************************************************************************
> File Name: ex8.8.cpp
> Author:
> Mail:
> Created Time: Sun 25 Feb 2024 12:26:50 PM CST
************************************************************************/
#include<iostream>
#include<fstream>
using namespace std;
struct Sales_data{
string isbn() const;
Sales_data& combine(const Sales_data&);
double avg_price() const;
string bookNo;
unsigned units_sold = 0;
double price = 0.0;
double revenue = 0.0;
};
string Sales_data::isbn() const{
return this->bookNo;
}
Sales_data& Sales_data::combine(const Sales_data &rhs){
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
double Sales_data::avg_price() const{
if(units_sold){
return revenue / units_sold;
}
else{
return 0;
}
}
Sales_data add(const Sales_data &sd1, const Sales_data &sd2){
Sales_data t = sd1;
t.combine(sd2);
return t;
}
ostream &print(ostream &output, const Sales_data &sd){
output<<sd.bookNo<<" "<<sd.units_sold<<" "<<sd.price<<" "<<sd.revenue<<" "<<sd.avg_p
return output;
}
istream &read(istream &input, Sales_data &sd){
input>>sd.bookNo>>sd.units_sold>>sd.price;
sd.revenue = sd.price * sd.units_sold;
return input;
}
int main(int argc, char *argv[]){
if(argc < 2){
cerr<<"No File Name."<<endl;
return -1;
}
ifstream in(argv[1]);
ofstream out("8.7.txt", ofstream::app);
if(!in){
cerr<<"Cannot open file!"<<endl;
return -1;
}
Sales_data total;
if(read(in, total)){
Sales_data trans;
while(read(in, trans)){
if(total.isbn() == trans.isbn()){
total.combine(trans);
}
else{
print(out, total)<<endl;
total = trans;
}
}
print(out, total)<<endl;
}
else{
cout<<"No data?!"<<endl;
}
return 0;
}