/* * Read a file that contains lines of the form * last, first * Output those lines into another file, in the * form first last * Illustrates reference parameters, input files, output files * This program is deliberately missing comments. */ #include #include #include using namespace std; void openInput( string & infile, ifstream & fin ); void openOutput( string infile, string outfile, ofstream & fout ); void copyFiles( istream & fin, ostream & fout ); void getNames( string name, string & first, string & last ); int main( ) { string infile; // Input file name string outfile; // Output file name ifstream fin; // Input file stream ofstream fout; // Output file stream openInput( infile, fin ); openOutput( infile, outfile, fout ); copyFiles( fin, fout ); return 0; } /** * Usual stuff; you should copy this. */ void openInput( string & infile, ifstream & fin ) { for( ; ; ) { cout << "Enter the input file name: "; cin >> infile; fin.open( infile.c_str( ) ); if( !fin ) { cout << "Bad file." << endl; fin.clear( ); } else break; } } /** * Usual stuff. This routine also checks to * make sure that outfile is different from infile. * To avoid this test, call it with infile equal to "". */ void openOutput( string infile, string outfile, ofstream & fout ) { for( ; ; ) { cout << "Enter the output file name: "; cin >> outfile; if( infile == outfile ) { cout << "Input and output files are identical!!" << endl; continue; } fout.open( outfile.c_str( ) ); if( !fout ) { cout << "Bad file." << endl; fout.clear( ); } else break; } } /** * Copy from fin to fout. * Uses getline to read an entire line of input in as a string. * Needed because there are blanks on the line. * getline also works with cin. */ void copyFiles( istream & fin, ostream & fout ) { string name, firstName, lastName; while( !getline( fin, name ).eof( ) ) { getNames( name, firstName, lastName ); fout << firstName << " " << lastName << endl; } } /** * Extract firstName and lastName from name. * pre: name is of the form last, first * post: lastName and firstName are filled in. */ void getNames( string name, string & firstName, string & lastName ) { int commaPos = name.find( "," ); lastName = name.substr( 0, commaPos ); firstName = name.substr( commaPos + 2, name.length( ) - ( commaPos + 2 ) ); }