
Sally J.
asked 10/19/21program that will read in the quantities and prices items from a file then calculates the total price
Write a C++ program that will read in the quantities and prices items from a file then calculates the total price (quantity * price) for each item and saves it in another file including the quantity and price. Last line includes the total for all items.
1 Expert Answer
Rize S. answered 03/23/23
25 Yrs Exp + MISM: General Computer Expert
Here's an example C++ program that reads in a file named "items.txt" with the format "quantity price" on each line, calculates the total price for each item, and saves the results to a file named "item_totals.txt". The program also outputs the total cost of all items to the console.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
// Open input file
ifstream inputFile("items.txt");
// Open output file
ofstream outputFile("item_totals.txt");
// Check if files are opened successfully
if (!inputFile.is_open()) {
cout << "Error opening input file!" << endl;
return 1;
}
if (!outputFile.is_open()) {
cout << "Error opening output file!" << endl;
return 1;
}
// Declare variables
int quantity;
double price, total = 0;
// Read in data from input file and calculate totals
while (inputFile >> quantity >> price) {
double itemTotal = quantity * price;
outputFile << quantity << " " << price << " " << fixed << setprecision(2) << itemTotal << endl;
total += itemTotal;
}
// Close files
inputFile.close();
outputFile.close();
// Output total cost of all items
cout << "Total cost of all items: $" << fixed << setprecision(2) << total << endl;
return 0;
}
Note that this program assumes that the input file is formatted correctly and contains only integer quantities and double prices separated by a space on each line. It also assumes that the output file can be created without issue. You may need to modify the code to handle different file formats or error conditions.
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Tom O.
10/24/21