-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy path8.07.cpp
70 lines (63 loc) · 1.55 KB
/
8.07.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* Exercise 8.7: Revise the bookstore program from the previous section to
* write its output to a file. Pass the name of that file as a second argument
* to main.
*
* By Faisal Saadatmand
*/
#include <iostream>
#include <fstream>
#include <string>
struct Sales_data {
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
int main(int argc, char **argv)
{
Sales_data total;
double averagePrice = 0.0;
double price = 0.0;
if (--argc != 2) {
std::cerr << "Usage: " + std::string(*argv) +
" <input_file> <output_file>\n";
return -1;
}
auto p = argv + 1;
std::ifstream input(*p);
if (!input) {
std::cerr << "Couldn't open " << *p << '\n';
return -1;
}
std::ofstream output(*++p);
if (!output) {
std::cerr << "Couldn't open " << *p << '\n';
return -1;
}
if (input >> total.bookNo >> total.units_sold >> price) {
total.revenue = total.units_sold * price;
Sales_data trans;
while (input >> trans.bookNo >> trans.units_sold >> price) {
trans.revenue = trans.units_sold * price;
if (total.bookNo == trans.bookNo) {
total.units_sold += trans.units_sold;
total.revenue += trans.revenue;
averagePrice = total.revenue / total.units_sold;
} else {
output << total.bookNo << " "
<< total.units_sold << " "
<< total.revenue << " "
<< averagePrice << std::endl;
total = trans;
}
}
output << total.bookNo << " "
<< total.units_sold << " "
<< total.revenue << " "
<< averagePrice << std::endl;
} else {
std::cerr << "No data?!" << std::endl;
return -1;
}
return 0;
}