C++ Primer(第5版) 练习 8.7
练习 8.7 修改上一节的书店程序,将结果保存到一个文件中。将输出文件名作为第二个参数传递给main函数。
环境:Linux Ubuntu(云服务器)
工具:vim
代码块
# 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" ) ;
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 ;
}
运行结果显示如下