The example that I mentioned that you would like to see ...
// input1.txt
/*
1 2 3 4 4 5 6 7 7 7 8 9 10 20 25
*/
// input2.txt
/*
1 2 5 5 9 9 10 11 12 13 14 14 15 15 15 16 17 18 19 20 21
*/
void mergeFiles( ifstream& fin1, ifstream& fin2, ofstream& fout )
{
int i1, i2, countIn = 0, countOut = 0;
if( fin1 >> i1 ) ++ countIn;
// Now firstly ... handle case of ... if empty file 1 ... //
if( fin1 ) // i.e. count == 1
{
// Then ... handle case of ... if empty file 2 ... //
if( fin2 >> i2 )
{
++ countIn;
while( fin1 && fin2 )
{
if( i1 <= i2 )
{
fout << i1 << ' ';
++countOut;
if( !(fin1 >> i1) )
{
fout << i2 << ' ';
++countOut;
//break; // handled by while ... above //
}
else ++countIn;
}
else
{
fout << i2 << ' ';
++countOut;
if( !(fin2 >> i2) )
{
fout << i1 << ' ';
++countOut;
//break; // handled by while ... above //
}
else ++countIn;
}
}
}
else
{
fout << i1 << ' '; // Do NOT forget to write this //
++countOut;
}
}
// check end conditions ... at most below, one line gets executed ... //
while( fin1 >> i1 ) { fout << i1 << ' '; ++countIn; ++countOut; }
while( fin2 >> i2 ) { fout << i2 << ' '; ++countIn; ++countOut; }
// 'in' and 'out' counts *should* match if all 'in' was 'out' ok ... //
cout << "countIn = " << countIn << endl;
cout << "countOut = " << countOut << endl;
}