(third part)
Open both file streams in main and pass them as parameters (must be a reference) to
a function that does all of the reading of the input, the calculations (using
FindAverage), and the writing of output. Thus your program will have 2 functions
other than main.
Your program should not specify where the data files are located. Rather, use the
default location (which is where your .cpp file is located).
When opening a file, always check to see if the open failed. If so, print an
appropriate error message and exit from the program.
Note that you will have to have both the input and output files open for much of this
program.
#include <iostream>
#include <fstream>
using namespace std;
void readInput(ofstream myfile){
if (myfile.is_open())
{
myfile << "Writing this to file.\n";
myfile.close();
}
else cout <<"The file failed to open.";
}
void writeOutput(ifstream infile){
string srg;
if (infile.is_open())
{
while ( getline (infile,srg) )
{
cout << srg <<endl;
}
infile.close();
}
else {
cout << "The file failed to open"<<endl;
}
}
int main()
{
ofstream outfile;
outfile.open ("example1.txt");
ifstream inpfile;
inpfile.open("example2.text");
readInput(outfile);
writeOutput(inpfile);
return 0;
}
Comments
Leave a comment