So i have an assignment to take two input files and combine into one output file in alphabetical order.
Example
File1.txt
Adam B Exam 80
Jane D Exam 87
Tom G Exam 77
File2.txt
George S Exam 99
Bob C Exam 67
Output.txt
Adam B
Bob C
George S
Jane D
Tom G
I have tried for hours to get this to work i think i might be on the correct path.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int openFiles (string inFile1, string inFile2, string outFile1);
void mergeFiles (string inFile1, string inFile2, string outFile1,ifstream& File1,ifstream& File2,ofstream& outFile);
int main()
{
string inFile1, inFile2, outFile1;
ifstream File1;
ifstream File2;
ofstream outFile;
cout <<"Enter input file 1:"<<endl;
cin >>inFile1;
cout <<"Enter input file 2:"<<endl;
cin >>inFile2;
cout <<"Enter output file 1:"<<endl;
cin >>outFile1;
openFiles (inFile1, inFile2, outFile1);
mergeFiles (inFile1, inFile2, outFile1, File1, File2, outFile);
return 0;
}
void mergeFiles (string inFile1, string inFile2, string outFile1,ifstream& File1,ifstream& File2,ofstream& outFile)
{
File1.open(inFile1.c_str());
File2.open(inFile2.c_str());
outFile.open(outFile1.c_str());
string File1_fName, File1_lName,exam1,examGrade1;
string File2_fName, File2_lName,exam2,examGrade2;
File1 >> File1_fName >> File1_lName>>exam1>>examGrade1;
File2 >> File2_fName >> File2_lName>>exam2>>examGrade2;
while (!File1.eof() && !File2.eof())
{
if ((File1_fName<=File2_fName ))
{
outFile << File1_fName << '\t'<< File1_lName << endl;
File1 >> File1_fName >> File1_lName>>exam1>>examGrade1;
}
else
{
outFile << File2_fName << '\t'<< File2_lName << endl;
File2 >> File2_fName >> File2_lName>>exam2>>examGrade2;
}
if (File1.eof() )
{
while (!File2.eof())
{
outFile << File2_fName << '\t'<< File2_lName << endl;
}
}
if (File2.eof() )
{
while (!File1.eof())
{
outFile << File1_fName << '\t'<< File1_lName << endl;
}
}
File1.close();
File2.close();
outFile.close();
}
}
int openFiles (string inFile1, string inFile2, string outFile1)
{
ofstream outFile;
outFile.open (outFile1.c_str());
if (outFile.fail())
{
cerr << "ERROR: cannot open " <<outFile1
<< " for output." <<endl;
return EXIT_FAILURE;
}
ifstream File1;
File1.open (inFile1.c_str());
if (File1.fail())
{
cerr << "ERROR: cannot open " <<inFile1
<< " for input." <<endl;
return EXIT_FAILURE;
}
ifstream File2;
File2.open (inFile2.c_str());
if (File2.fail())
{
cerr << "ERROR: cannot open " <<inFile2
<< " for input." <<endl;
return EXIT_FAILURE;
}
}