// Oldham, Jeffrey D. // 2000 Jan 04 // CS1321 // CS1321 Homework 1: Compute Sales Tax // Compute the sales tax for a given list of item prices in a given state. // Command line arguments: // 1. name of file containing states and sales tax rates // 2. name of the state for the transaction // 3. any number of item prices written as decimals with two decimal points // Revisions: // 2000Jan24: round() does not work correctly for negative numbers. // Since setprecision() apparently works correctly, we need not worry // any more. #include #include #include // has strtod() #include #include // Find the sales tax rate in the file corresponding to the state. // Return a negative number if no rate is found. double salesTaxRate(const string & filename, const string & state); // I cannot find the library containing round() so I will write my own // function. :( // 2000Jan24: does not work correctly for negative numbers :( double round(const double d) { return static_cast(d + 0.5); } int main(int argc, char *argv[]) { if (argc < 3) { cerr << argv[0] << ": sales-tax-file state item-prices ...\n"; exit(EXIT_FAILURE); // I found this EXIT_FAILURE macro recently. } // Determine the sales tax rate. double rate; if ((rate = salesTaxRate(argv[1], argv[2])) < 0) { cerr << argv[0] << ": sales tax rate for " << argv[2] << " not found\n"; exit(EXIT_FAILURE); } // Determine the total item cost. double cost = 0.0; for (int i = 3; i < argc; ++i) cost += strtod(argv[i], static_cast(0)); // Print the answer. cout.setf(std::ios::fixed); // JDO 2000Jan24: cout << setprecision(2) << round(cost * rate) / 100.0 << endl; cout << setprecision(2) << cost * rate / 100.0 << endl; return 0; } // Find the sales tax rate in the file corresponding to the state. // Return a negative number if no rate is found. double salesTaxRate(const string & filename, const string & state) { ifstream in(filename.c_str()); if (!in) { cerr << "Failed to open " << filename << ".\n"; exit(EXIT_FAILURE); } string abbrev; double rate; while ((in >> abbrev >> rate) && (abbrev != state)) ; in.close(); if (abbrev == state) return rate; else return -1.0; }