I'm having a problem with merging two text files into a third file. I created two separate text files with five integers each, already sorted.
i.e.
1
2
4
7
9
and
2
4
4
6
8
I need to check each file for the smaller number and add it to a third file in ascending order.
i.e.
1224446789
My current output is this:
12244467
It's not getting to the end of each file. I'm having a problem with the eof() function. I think it's either not reaching the end of the file, or just stopping for some reason. Any help would be appreciated. Here's my code so far:
#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
ifstream file1; //declare fstream variables
ifstream file2;
ofstream outFile;
int data1, data2; //declare int variables for reading and writing ints
file1.open("textFile1.txt"); //open files for input operations
file2.open("textFile2.txt");
if (file1.fail() || file2.fail()){ //check for failure to open
cout << "Error opening file.";
}
outFile.open("out.txt"); //open out file for output operations
if (outFile.fail()){
cout << "Outfile open failed.";
}
file1 >> data1; //read file1 and first integer
file2 >> data2; //read file2 and first integer
while (!file1.eof() || !file2.eof()) //I think my problem lies here
{
if (data1 <= data2) //check if data1 <= data2
{
outFile << data1; //if so, record data1
file1 >> data1; //read file1 again
}
elseif (data1 >= data2) //check if data1 >= data2
{
outFile << data2; //if so, record data2
file2 >> data2; //read data2 again
}
elseif (file1.eof()) //check if you are at the end of file1
{
if(!file2.eof()) //while not at the end of file2,
//record data2
{
outFile << data2;
}
}
elseif (file2.eof()) //check if you are at the end of file2
{
if(!file1.eof()) //while not at the end of file1,
//record data1
{
outFile << data1;
}
}
}
file1.close(); //close all files
file2.close();
outFile.close();
return 0;
}
Lines 39 and 47 (and the bodies of those blocks) in your code will never be reached. data1 will always be either less than, greater than or equal to data2.
If I had to do it the way you're doing it (without using containers) I'd probably do something more like this:
.
.
file1 >> data1; //read file1 and first integer
file2 >> data2; //read file2 and first integer
while (!file1.eof() || !file2.eof()) //I think my problem lies here
{
.
.