Hello,
I'm having a little trouble with a some code that I'm writing for homework. Basically, I'm taking two files that contain numbers and merging the contents into another file. The files do not have the same amount of numbers in them (one might contain 7 while the other contains 10) and the numbers are sorted from small to large in each file al ready. My problem is that not all the numbers are being written to the output file. Here is the code below:
#include <iostream>
#include <fstream>
using namespace std;
void MergeFiles(ifstream&, ifstream&, ofstream&);
int main()
{
ifstream input_file1, input_file2;
ofstream output_file;
input_file1.open("input1.txt");
input_file2.open("input2.txt");
output_file.open("output.txt");
if (input_file1.fail())
{
cerr << "Error opening file."<< endl;
exit(1);
}
if (input_file2.fail())
{
cerr << "Error opening file."<< endl;
exit(1);
}
MergeFiles(input_file1, input_file2, output_file);
cout << "Please see output.txt for merged view of input1.txt and input2.txt.";
input_file1.close();
input_file2.close();
output_file.close();
return 0;
}
void MergeFiles(ifstream& input_file1, ifstream& input_file2, ofstream& output_file)
{
int num1, num2;
input_file1 >> num1;
input_file2 >> num2;
while(!input_file1.eof() || !input_file2.eof())
{
if (num1 <= num2)
{
output_file << num1;
output_file << endl;
input_file1 >> num1;
}
else
{
output_file << num2;
output_file << endl;
input_file2 >> num2;
}
}
}
I know the problem is with the while loop, but I can't figure it out. Any help would be appreciated.