本节源码位于avg_price.cpp中
1 #include <iostream> 2 #include "Sales_item.h" 3 4 int main12() 5 { 6 Sales_item total; // variable to hold data for the next transaction 7 8 // read the first transaction and ensure that there are data to process 9 if (std::cin >> total) { 10 Sales_item trans; // variable to hold the running sum 11 // read and process the remaining transactions 12 while (std::cin >> trans) { 13 // if we're still processing the same book 14 if (total.isbn() == trans.isbn()) 15 total += trans; // update the running total 16 else { 17 // print results for the previous book 18 std::cout << total << std::endl; 19 total = trans; // total now refers to the next book 20 } 21 } 22 std::cout << total << std::endl; // print the last transaction 23 } else { 24 // no input! warn the user 25 std::cerr << "No data?!" << std::endl; 26 return -1; // indicate failure 27 } 28 29 return 0; 30 }