countw3.cc From Astrachan, pp 270-272 ------------------------------------- #include #include #include "CPstring.h" #include "prompt.h" // count words in stream bound to text file // uses a WordStreamIterator class to hide I/O details class WordStreamIterator { public: WordStreamIterator(); void Open(string name); // bind stream to specific text file void First(); // initialize iterator string Current(); // returns current word bool IsDone(); // true if iterator is done void Next(); // advance to next word private: string myWord; // the current word bool myDone; // true if no more words ifstream myInput; // the stream to read from }; WordStreamIterator::WordStreamIterator() // postcondition: iterator is initialized, IsDone() == true { myWord = ""; myDone = true; // First() must be called } void WordStreamIterator::Open(string name) { myInput.open(name); } void WordStreamIterator::First() // postcondition: first word read from stream myInput { myInput.seekg(0); // back to beginning myInput.clear(); // clear the stream myDone = ! (myInput >> myWord); // read first word, set state } string WordStreamIterator::Current() // precondition: IsDone() == false // postcondition: returns current word { return myWord; } bool WordStreamIterator::IsDone() // postcondition: returns true if no words left in stream // (all words have been read) otherwise returns false { return myDone; } void WordStreamIterator::Next() // precondition: ! IsDone() // postcondition: next word from stream myInput read { if (! IsDone()) { myDone = ! (myInput >> myWord); } } int main() { string word; int numWords = 0; // initially, no words WordStreamIterator iter; iter.Open(PromptString("enter name of file: ")); for(iter.First(); ! iter.IsDone(); iter.Next()) { numWords++; } cout << "number of words read = " << numWords << endl; return 0; }