0

I have tried many variations of this code and as well as displaying every single step to the screen in attempt to fix my mistakes, yet the do-while loop still ends early and doesn't read the entire file.. Any tips for a newcomer in C++? By the way, I amm using two files with the following code: input1.dat & input2.dat - each file filled with 10 numbers on seperate lines. Thanks in advance! :]

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

void merger(ifstream& in1, ifstream& in2, ofstream& out);

int main()
{
    ifstream in1, in2;
    ofstream out;

    in1.open("input1.dat");
    if (in1.fail())
    {
        cout << "Opening input file failed." << endl;
        exit(1);
    };

    in2.open("input2.dat");
    if (in2.fail())
    {
        cout << "Opening input file failed." << endl;
        exit(1);
    };

    out.open("results.dat");
    if (out.fail())
    {
        cout << "Opening output file failed." << endl;
        exit(1);
    };

    merger(in1, in2, out);
    in1.close();
    in2.close();
    out.close();

}

void merger(ifstream& in1, ifstream& in2, ofstream& out)
{
    int one, two, three;
    in1 >> one;
    in2 >> two;

    do
    {
        if(one < two)
        {
            three = one;
            out << three << endl;
            cout << three << endl;
            in1 >> one;
                if(in1.eof())
                {
                cout << "end of file 1" << endl;
                }
        } else {
            three = two;
            out << three << endl;
            cout << three << endl;
            in2 >> two;
                if(in2.eof())
                {
                cout << "end of file 2" << endl;
                }
        }
    }while(!in1.eof() || !in2.eof());
}
Doja_Dre
  • 1
  • 1
  • possible duplicate of [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Tony Delroy May 08 '13 at 01:16
  • I can understand why using not EOF instead of something like (cin >> next) is wrong.. but the question still remains on why it is only reading 9 lines of code then reading false, instead of 10. – Doja_Dre May 08 '13 at 03:38
  • the reason is that you read a new value to replace `one` or `two` then exit if you're at the EOF without having used the value.... – Tony Delroy May 08 '13 at 04:09

0 Answers0