/* * 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 "apstring.h" void OpenInput( apstring & infile, ifstream & fin ); void OpenOutput( apstring infile, apstring outfile, ofstream & fout ); void CopyFiles( istream & fin, ostream & fout ); void GetNames( apstring Name, apstring & First, apstring & Last ); int main( ) { apstring infile; // Input file name apstring 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( apstring & infile, ifstream & fin ) { for( ; ; ) { cout << "Enter the input file name: "; cin >> infile; fin.open( infile.c_str( ), ios::in | ios::nocreate ); 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( apstring infile, apstring 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 ) { apstring Name, FirstName, LastName; while( !getline( fin, Name ).eof( ) ) { GetNames( Name, FirstName, LastName ); fout << FirstName << " " << LastName << endl; } } /** * I did this in class. Extract FirstName and LastName from Name. * pre: Name is of the form Last, First * post: LastName and FirstName are filled in. */ void GetNames( apstring Name, apstring & FirstName, apstring & LastName ) { int CommaPos = Name.find( "," ); LastName = Name.substr( 0, CommaPos ); FirstName = Name.substr( CommaPos + 2, Name.length( ) - ( CommaPos + 2 ) ); }