// Simulate a grocery store checkout system with item info // stored in a file and items purchased provided through // standard input. // Beth Katz, April 2006 #include #include #include ; using namespace std; struct itemInfo { int number; string name; double price; string type; }; // set up default output format and precision of digits after decimal void setOutputFormat(int digits); // obtain the database file name from the user and fill the // item database with the information in the file void fillItemDatabase(vector & items); // process an order of several items void processOrder(const vector & items); // lookup a single item and return its index // returns vector size if itemNumber is not found unsigned int lookupItem(const vector & items, int itemNumber); // print information about one item purchase void printItem(const itemInfo & item, double quantity, double cost); int main( ) { vector items; setOutputFormat(2); fillItemDatabase(items); processOrder(items); return 0; } // set up default output format and precision of digits after decimal void setOutputFormat(int digits) { cout.precision(digits); cout.setf(ios::fixed | ios::dec | ios::showpoint); } // obtain the database file name from the user and fill the // item database with the information in the file void fillItemDatabase(vector & items) { ifstream datafile; string filename; itemInfo i; cout << "Enter file name: "; cin >> filename; datafile.open(filename.c_str( )); if ( datafile.fail( ) ) { cout << "Cannot open data file: " << filename << endl; exit(1); } while (datafile >> i.number >> i.name >> i.price >> i.type) { items.push_back(i); } datafile.close(); } // process an order of several items void processOrder(const vector & items) { double total = 0.0; int itemNumber; double quantity; unsigned int index; double cost; while (cin >> itemNumber >> quantity) { index = lookupItem(items, itemNumber); if (index == items.size( )) { cout << "Item " << itemNumber << " unknown. Skipping." << endl; } else if (quantity <= 0) { cout << quantity << " is not positive. Skipping." << endl; } else { cost = items[index].price * quantity; total += cost; printItem(items[index], quantity, cost); } } cout << endl << "Total = $" << total << endl; } // lookup a single item and return its index // returns items vector size if itemNumber is not found unsigned int lookupItem(const vector & items, int itemNumber) { unsigned int i; for (i = 0; (i < items.size( )) && (items[i].number != itemNumber); i++) { } return i; } // print information about one item purchase void printItem(const itemInfo & item, double quantity, double cost) { cout << item.name << " "; if (item.type == "pounds") { cout << quantity << " lb" << " @ " << item.price << "/lb"; } else { cout << int(quantity) << " @ " << item.price << " each"; } cout << " = $" << cost << endl; }