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.

Recommended Answers

All 3 Replies

After the loop you posed finishes you have to finish reading from the file that has not yet reached EOF and writing it's data to the output file. You need to add more code after line 65 to do that.

you have to check if all the contents of both files are written into the output file before the ending of the function. If not the write them into the file. I think the problem will get solved.

you have not handled a case where suppose one file reaches eof and the other does not.You need to keep track of which file has reached eof and then acordingly take input from the other file till it reaches its eof.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.