The purpose of this assignment is to make sure that you know how to write a prog
ID: 3853062 • Letter: T
Question
The purpose of this assignment is to make sure that you know how to write a program that uses files and file processing. The program also contains functions and does input, output, flow of control and/or calculations. PROGRAM SPECIFICATION For the assignment, we will write a program that reads a file of information pertaining to a Farmer's Market. The file contains the names of various farms participating in a Farmer's Market. The program should create a file object for input, read the data, perform some calculations, create a report, and then rewrite the information to a new output file The format of the file is as follows: Field or data item in the file Data type String of characters Integer Notes Farm name This could end with a comma Count of item Number of items Item String Name of the item Item price Float or double Unit cost of each itemExplanation / Answer
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <cstdlib>
using namespace std;
vector<string> split(string str, char delim) {
vector<string> queue;
stringstream sstream(str); // Turn the string into a stream.
string tok;
while(getline(sstream, tok, delim)) {
queue.push_back(tok);
}
return queue;
}
string trim(string str) {
stringstream ss;
ss << str;
string s;
string out;
while(ss >> s) {
out+=(s+' ');
}
return out.substr(0, out.length()-1);
}
int main (int argc, char *args[]) {
string line;
ifstream inFile (args[1]); // Give input file on command line at first arguement.
ofstream outFile;
outFile.open ("output.txt");
if (inFile.is_open())
{
while ( getline (inFile,line) )
{
vector<string> record = split(line, ','); // Get name
vector<string> item = split(trim(record[1]), ' '); //Get items
string report = record[0] + ": " + item[0] + " " + item[1] + " @ " + item[2] +
" each totalling $";
cout << report;
cout << atof (item[2].c_str()) * atof (item[0].c_str()) << ' '; // Report log to the command line
outFile << report << atof (item[2].c_str()) * atof (item[0].c_str()) << ' '; // Writing into the output file
}
inFile.close();
outFile.close();
}
else cout << "Can't open file";
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.