C++ Read multiple inputs from one line of a file program Lab Instructions Create
ID: 3588125 • Letter: C
Question
C++ Read multiple inputs from one line of a file program
Lab Instructions
Create one file, lab6.cpp. This program should accept two command line arguments: an input text file and an output text file for writing results. You will be given an input file of variable length that contains records from a book auction service. Each line will contain a record of the form:
1 $43.50 $74.50 $33.60 The Dark Tower
2 $23.15 $43.32 $19.53 Lord of the Rings Return of the King
3 $32.34 $50.65 Ender's Game
4 $21.50 $32.92 Clash of Kings
5 $34.32 $31.21 $37.43 $19.99 Feast for Crows
6 $28.50 $22.92 Hitchhiker's Guide to the Galaxy
Each record begins with an ID, a variable list of auction prices, and a book title.
You may only use C++ style file I/O to manipulate data. You may not use printf or scanf in your program.
Your Objectives
• Read through the input file breaking each line into its components
• Find the average of all the list prices for each book
• Print out a formatted record for each book, using setw() and other manipulators
• If a book title is too long, replace the end of the title with “…”
Explanation / Answer
save the below code lab6.cpp, compile and run. kepp input.txt & output.txt in the same directory
while executing pass the command line argument as
./a.out input.txt output.txt
Note: input.txt should be as per your program
/*****************************/
#include <iomanip>
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <stdlib.h>
using namespace std;
int main(int argc,char* argv[])
{
ifstream ifp(argv[1]);
ofstream ofp(argv[2]);
while(!ifp.eof())
{
string str;
getline(ifp,str);
istringstream iss(str);
int count=0,avgcount=0;
float price=0.0;
string name="";
do
{
string sub;
iss>>sub;
if(count==0)
{
ofp<<sub;
}
else if((count>0)&& *sub.begin()=='$')
{
ofp<<sub;
sub.erase(0,1);
price=price+atof(sub.c_str());
avgcount++;
}
else if(count>0)
{
name=name+sub;
}
count++;
}while(iss);
ofp<<setw(20)<<name; // try yourself the last question; put a comment in comment section if any difficulty
ofp<<" Average: price $"<<(price/avgcount)<<endl;
}
return 0;
}
/*********************************/input.txt
1 $43.50 $74.50 $33.60 The Dark Tower
2 $23.15 $43.32 $19.53 Lord of the Rings Return of the King
3 $32.34 $50.65 Ender's Game
4 $21.50 $32.92 Clash of Kings
5 $34.32 $31.21 $37.43 $19.99 Feast for Crows
6 $28.50 $22.92 Hitchhiker's Guide to the Galaxy
/****************************/output.txt
this file is optional. program will create this file
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.