Write a function called solveFile(Inputfilename, outputfilename). It takes two s
ID: 3772022 • Letter: W
Question
Write a function called solveFile(Inputfilename, outputfilename). It takes two string para met are which are filenames. The Input file will have multiple lines, where each line will be of the form a number, followed by a space, followed by one of 'add' or 'sub', followed by a space, followed by another number. The numbers will be whole numbers for e.g. a possible input file could have 23 add 7 10 add 9 3 sub 2 5 add 4 Your function should go through this file and create the output file, where each line will be the answer to the line In the input file. for the above example, the output file should have 30 19 1 9 Your function does not return anythingExplanation / Answer
Answer:
Note: PROGRAMMING LANGUAGE HAS NOT BEEN MENTIONED. HENCE IMPLEMENTED IN C++
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
void solveFile(string inputfilename,string outputfilename)
{
//DECLARE VARIABLES
int op1,op2,result=0;
string operation;
//OPEN THE FILES
ifstream infile(inputfilename.c_str());
ofstream outfile(outputfilename.c_str());
//CHECK IF INPUTFILE IS OPEN
if(infile.is_open())
{
//READ FROM INPUTFILE LINE BY LINE
while(infile>>op1>>operation>>op2)
{
//ADD
if(operation=="add")
result=op1+op2;
//SUB
else if(operation=="sub")
result=op1-op2;
//WRITE THE RESULT TO THE OUTPUTFILE
outfile<<result<<endl;
}
}
//CLOSE THE FILES
infile.close();
outfile.close();
}
//MAIN METHOD
int main()
{
string inputfilename,outputfilename;
//GET INPUT FILE NAME
cout<<"ENTER INPUTFILENAME"<<endl;
cin>>inputfilename;
//GET THE OUTPUT FILENAME
cout<<"ENTER OUTPURFILENAME"<<endl;
cin>>outputfilename;
//CALL THE FUNCTION
solveFile(inputfilename,outputfilename);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.