/** * Assignment #7 * Program to sort strings * Author: Mark Allen Weiss * SSN: 000-00-0000 * Course: COP-2210 Section 8 * Date: November 1, 1998 * * CERTIFICATION OF SOLE AUTHORSHIP * I certify that this work is solely my own and * that none if it is the work of any other person. * I further certify that I have not provided any * assistance to other students enrolled in COP-2210 that * would render their CERTIFICATION OF SOLE AUTHORSHIP * invalid. I understand that violations of this pledge * may result in severe sanctions. * * * * ----------------------------------- * (Mark Allen Weiss) <--- Put your name here, and sign above */ #include #include #include "apstring.h" #include "apvector.h" void OpenInput( apstring & infile, ifstream & fin ); void OpenOutput( apstring infile, apstring outfile, ofstream & fout ); void ProcessFile( istream & fin, ostream & fout ); void Sort( apvector & A ); 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 ); ProcessFile( 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; } } /** * Read from fin; write sorted output to fout. * Pre: fin and fout are open and ready for reading and writing, respectively. */ void ProcessFile( istream & fin, ostream & fout ) { apvector Array( 100 ); int ItemsRead = 0; apstring X; while( fin >> X ) { if( ItemsRead == Array.length( ) ) Array.resize( Array.length( ) * 2 ); Array[ ItemsRead ] = X; ItemsRead++; } Array.resize( ItemsRead ); Sort( Array ); for( int i = 0; i < Array.length( ); i++ ) fout << Array[ i ] << endl; } /** * Insertion sort (different than in text and in class). * Selection sort would be an acceptable alternative. */ void Sort( apvector & A ) { for( int p = 1; p < A.length( ); p++ ) { apstring tmp = A[ p ]; int j; for( j = p; j > 0 && tmp < A[ j - 1 ]; j-- ) A[ j ] = A[ j - 1 ]; A[ j ] = tmp; } }