Solution to Problem 1
#include <iostream.h>
#include <fstream.h>
#include "mystring.h"
//copy the rest of the file into target file
void copyfile( ifstream &input, ofstream &output )
{
string str;
while( input >> str )
output << str << endl;
}
int main()
{
ifstream f1, f2;
ofstream f3;
string a, b;
f1.open( "names1.dat" );
f2.open( "names2.dat" );
f3.open( "names3.dat" );
//read the first names from both files
f1 >> a;
f2 >> b;
while( 1 ) {
if( a > b )
{
f3 << b << endl;
if ( !( f2 >> b ) )
{
f3 << a << endl;
copyfile( f1, f3 );
return 0;
}
}
else if( a < b )
{
f3 << a << endl;
if( !( f1 >> a ) )
{
f3 << b << endl;
copyfile( f2, f3 );
return 0;
}
}
else
{
f3 << a << endl;
if( !( f1 >> a ) )
{
f3 << b << endl;
copyfile( f2, f3 );
return 0;
}
if (!( f2 >> b ) )
{
f3 << a << endl;
copyfile( f1, f3 );
return 0;
}
}
}
}
Solution to Problem 2
6.15
Since the two parameters of function Change: first and second are passed by reference, when function call Change(num,num) is made, both first and second are aliases for the same variable num. Initially, num=8, after first += 2, num=8+2=10; after second *= 2, num =10*2=20. So the output will be 20.
When num is initialized to 3, the same thing happens, the result is (3+2)*2= 10.
6.17
void Swap( int &a, int &b ) { int t; t = a; a = b; b = t; }