用.eof()循环的早期结束?

时间:2013-05-08 01:04:35

标签: c++ loops eof do-while

我已尝试过此代码的多种变体,并且在屏幕上显示每一步以尝试修复我的错误,但是do-while循环仍然提前结束并且不会读取整个文件..任何提示对于C ++的新手?顺便说一下,我使用以下代码的两个文件:input1.dat& input2.dat - 每个文件在单独的行上填充10个数字。 提前致谢! :]

#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());
}

0 个答案:

没有答案