/******************* Words are read in and written out in reverse order. A word contains only alphabetic characters. Command line syntax is: ./a.out [input-file [output-file]] input-file is the optional name of the input file (defaults to cin). If output-file is specified, the input file must also be specified. The output file defaults to cout if not specified. Examples: ./a.out ./a.out inputfile ./a.out inputfile outputfile *******************/ #include #include #include #include #include using namespace std; int main( int argc, char *argv[] ) { istream *infile = &cin; // pointer to input stream; default to cin ostream *outfile = &cout; // pointer to output stream; default to cout switch ( argc ) { case 3: outfile = new ofstream( argv[2] ); // open the outfile file if ( outfile->bad() ) { cerr << "Error! Could not open output file \"" << argv[2] << "\"" << endl; exit( -1 ); // TERMINATE! } // if // fall through to handle input file case 2: infile = new ifstream( argv[1] ); // open the first input file if ( infile->bad() ) { cerr << "Error! Could not open input file \"" << argv[1] << "\"" << endl; exit( -1 ); // TERMINATE! } // if break; case 1: // use cin and cout break; default: // too many arguments cerr << "Usage: " << argv[0] << " [input-file [output-file]]" << endl; exit( -1 ); // TERMINATE! } string line, alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; list words; // list of words in document for ( ;; ) { // scan lines from a file getline( *infile, line ); // read entire line, but not newline if ( infile->eof() ) break; // end-of-file ? line += "\n"; // add newline character as sentinel character for ( ;; ) { // scan words off line int posn = line.find_first_of(alpha); // find position of 1st alphabetic character if ( posn == -1 ) break; // any characters left ? line = line.substr( posn ); // remove leading whitespace posn = line.find_first_not_of(alpha); // find position of 1st non-alphabetic character string word = line.substr( 0, posn ); // extract word from start of line words.push_back( word ); // add word to end of list line = line.substr( posn ); // delete word from line } // for } // for *outfile << "The words in reverse order:" << endl; while ( 0 < words.size() ) { // traverse list in reverse order *outfile << *(--words.end()) << endl; // print last node words.erase( --words.end() ); // remove last node } // whille if ( infile != &cin ) delete infile; // do not delete cin if ( outfile != &cout ) delete outfile; // do not delete cout } // main // Local Variables: // // tab-width: 4 // // End: //