#include #include // for ifstream #include "CPstring.h" #include "prompt.h" #include "vector.h" // file: context3.cc // author Dietolf Ramm; date: 10/30/96, 10/31/96, 11/3/96 // read text, as words, into a vector // handle larger files with SetSize member function // interactively, display requested word with C words before and after. const int C = 3; // number of words to display on either side const string SENTINEL = "quit"; // word to cause exit from request loop void Load(Vector & text, int & size); void Display(const Vector & text, int size, int where); void Find(const Vector & text, int size, string request); int main() { int size; string request; Vector text(50); // only allocate 50 initially Load(text, size); cout << endl << "search word: "; cin >> request; while(request != SENTINEL) { Find(text, size, request); cout << endl << "search word: "; cin >> request; } return 0; } void Find(const Vector & text, int size, string request) // postcondition: for each match of request with text, Display invoked { int k; for (k = 0; k < size; k++) if (text[k] == request) Display(text, size, k); } void Display(const Vector & text, int size, int where) // postcondition: located word printed in context { int k, start, finish; start = where - C; if (start < 0) start = 0; finish = where + C; if (finish >= size) finish = size-1; for (k = start; k <= finish; k++) cout << text[k] << " "; cout << endl; } void Load(Vector & text, int & size) // postcondition: text contains words read in with size telling how many { string word; string filename = PromptString("Enter name of input file: "); ifstream input(filename); size = 0; while (input >> word) { if (size >= text.Length() ) // do we need to grow our vector? { text.SetSize(2*text.Length()); cout << "Size doubled to " << text.Length() << endl; } text[size] = word; size++; } cout << size << " words read." << endl; } Sample output: Enter name of input file: honor Size doubled to 100 Size doubled to 200 192 words read. search word: Duke Duke University Undergraduate Honor essential feature of Duke University is its citizen of the Duke University Community: I search word: quit