C++ and dont use classes Create a function named CalcCost, which takes a string
ID: 3854471 • Letter: C
Question
C++ and dont use classes
Create a function named CalcCost, which takes a string input filename and string output filename as a parameters. This function returns the number of entries read from the file. If the input file cannot be opened, return -1 and do not print anything to the output file. Read each line from the given filename, parse the data, process the data, and print the required information to the output file. Each line of the file contains PRODUCT NAME, COST PER ITEM, QUANTITY. Read and parse the data, then output the total cost for each entry. If given the data below: Seattle Coffee, 12.54, 39 Denver Mints, 1.00, 1877 Computer, 699.95, 16 Your output file should contain: Seattle Coffee: 489.06 Denver Mints: 1877.00 Computer: 11199.20 You only need to write the function code. Our code will create and test your class.
Explanation / Answer
//Test c++ program for calcCost method
#include<iostream>
#include<sstream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
///function prototype
int CalcCost(string inFile, string outFile);
//main method
int main()
{
//calling method
CalcCost("input.txt", "output.txt");
system("pause");
return 0;
}
/**
The function CalcCost that takes two string file names and read data from
inFile and writes to output file outFile if the no error in file opening of input
file inFile otherwise retunr -1 .
*/
int CalcCost(string inFile, string outFile)
{
//Open intput file
ifstream fin(inFile);
//checking if file doesnot exist
if(!fin)
{
return -1;
}
//open output file
ofstream fout("output.txt");
string line;
fout << std::fixed;
fout << std::setprecision(2);
//read data into line utnil end of file
while(getline(fin,line))
{
//set line to stringstream
stringstream linestream(line);
//declarea variables
string itemName;
string cost;
string quantity;
std::string::size_type sz;
//get itemName from linestream separated by comma
getline(linestream,itemName,',');
//get cost from linestream separated by comma
getline(linestream,cost,',');
//get qunatiyt from linestream separated by comma
getline(linestream,quantity,',');
//write itemName and total cost to output file
fout <<itemName<<", "<<stod(cost,&sz)*stod(quantity,&sz)<<endl;
}
}//end of function CalcCost
---------------------------------------------------------------------------------------------------------------------------
input.txt
Seattle Coffee, 12.54, 39
Denver Mints, 1.00, 1877
Computer, 699.95, 16
---------------------------------------------------------------------------------------------------------------------------
Sample output:
Seattle Coffee, 489.06
Denver Mints, 1877.00
Computer, 11199.20
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.