Assignment
•read an integer from input file 1.
•read an integer from input file 2.
•if both were successful:
◦Multiply these input values, and store the result.
◦Write the value in output file.
◦Add the value to an accumulator.
◦Increment a counter.
•If the input file 1 read was not good, and the eof has not been reached,
◦print “ERROR: “ and the counter variable.
◦End the loop.
•If the input file 2 read was not good and the end of the file has not been reached,
◦print “ERROR: “ and the counter variable.
◦End the loop.
•If the write to the output file was not good:
◦print “ERROR: “ and the counter variable.
◦End the loop.
After the loop, your program should print out “Program completed after “ counter“ numbers read.” The program should then let the user know if either file was not finished or if both were finished. The program should then print out the final accumulator value
#include <iostream>
#include <fstream>
using namespace std;
int main(){
//file names are hard coded
fstream file1("file1", ios::in), file2("file2", ios::in), output("output", ios::out);
int one, two, counter = 0, accumulator = 0;
if(!file1 || !file2){
cout<<"ERROR opening file\n";
return -1;
}
while(!file1.eof() && !file2.eof()){
if(!(file1>>one)){
cout<<"ERROR\n";
cout<<"Counter = "<<counter<<endl;
break;
}
if(!(file2>>two)){
cout<<"ERROR\n";
cout<<"Counter = "<<counter<<endl;
break;
}
if(!output){
cout<<"ERROR\n";
cout<<"Counter = "<<counter<<endl;
break;
}
int res = one * two;
counter++;
output<<res<<endl;
accumulator += res;
}
cout<<"Program completed after "<<counter<<" numbers read\n";
if(!file1.eof()) cout<<"File 1 not finished\n";
if(!file2.eof()) cout<<"File 2 not finished\n";
else if(file1.eof()) cout<<"Both files finished\n";
file1.close();
file2.close();
output.close();
cout<<"Accumulator value: "<<accumulator<<endl;
return 0;
}
Comments
Leave a comment