我已经尝试了此代码的许多变体,并且将每一步都显示到屏幕上以尝试修复我的错误,但是 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());
}