#include #include // for ifstream #include using namespace std; #include "prompt.h" #include "tvector.h" // file: context3.cpp // author Dietolf Ramm; date: 10/30/96, 10/31/96, 11/3/96 // read text, as words, into a vector // handle larger files with resize 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(tvector & text, int & size); void Display(const tvector & text, int size, int where); void Find(const tvector & text, int size, string request); int main() { int size; string request; tvector 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 tvector & 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 tvector & 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(tvector & 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.c_str()); size = 0; while (input >> word) { if (size >= text.capacity() ) // do we need to grow our vector? { text.resize(2*text.capacity()); cout << "Size doubled to " << text.capacity() << endl; } text[size] = word; size++; } cout << size << " words read." << endl; } /* Sample output: prompt> context3 Enter name of input file: context3.cpp Size doubled to 100 Size doubled to 200 Size doubled to 400 384 words read. search word: resize larger files with resize member function // search word: capacity search word: text.capacity() if (size >= text.capacity() ) // do to " << text.capacity() << endl; } search word: quit */