////////////////////////////////////////////////////////////////// // // getword.cpp // // Started by Jeff Ondich on 4/1/98 // Last modified 9/16/99 // // This program retrieves words from standard input // until reaching "end of file." You can run this // in two ways: // // (1) getword < somefile.txt // // (2) getword // // In the second case, you will type the input. You // can type as many lines as you like. To terminate // the input, type CTRL-D at the start of a new line. // ////////////////////////////////////////////////////////////////// #include #include bool GetWord( string& word ); int main( void ) { string myWord; while( GetWord( myWord ) ) { cout << myWord << endl; } return( 0 ); } ////////////////////////////////////////////////////////////////// // // GetWord retrieves the next word from standard input (cin), // returning true if there is a word remaining in the input, // and false if not. In the former case, the word is // returned via the reference parameter "word". // // GetWord defines a "word" to be any contiguous block of // letters, hyphens, and apostrophes that starts with a // letter. Thus, "don't" and "hocus-pocus" are both // considered words (as they should be), but so is // "Q--'--". Defining "word" better than this is // possible, but complicated. // // We'll talk about how GetWord works some time in class. // ////////////////////////////////////////////////////////////////// bool GetWord( string& word ) { char c; // Scan through the text until we find a letter. while( cin.get(c) && !isalpha(c) ) { // Just looping. There's not supposed to be anything // here in the loop body. All the work gets done // in the loop condition. } // If we reached the end of the file without finding // a word, return false. if( !cin ) return( false ); // Otherwise, build the word one character at a time // and return true. word = c; while( cin.get(c) && (isalpha(c) || c == '-' || c == '\'') ) { word = word + c; } return( true ); }