// File name: search.cpp // Author: Xiannong Meng // Course: CS2330 // Date: February 27, 1997 // Assignment: classroom discussion // Problem statement: This program takes a word from user, searchs // through a file, if it is found, the line is listed. #include #include #include #include #include #include // for getch() #include "./cstring/cstring.h" void hold() { int c; while (!kbhit()); c = getch(); } void main(void) { void SearchWord(String name, String w); String fileName; String word; cout << " type in a file name : "; cin >> fileName; cout << " type in a word to search : "; cin >> word; SearchWord(fileName,word); hold(); } // Name : SerachWord // Intent: search a word in a file // Pre: a word and a file name is given // Post: display the line if word is found void SearchWord(String fName, String word) { ifstream inF(fName.value()); // file to search char oLine[160]; String line; String compWord; int found = 0; int wLen = word.length(); int start, end; if (!inF) { cerr << " file open failed \n"; exit(1); } inF.getline(oLine,160,'\n'); int compLen = strlen(oLine); while (inF && (found == 0)) { cout << oLine << endl; start = 0; end = wLen; compWord.assign(oLine,start,end); while ((compWord != word) && (end < compLen)) { start ++; end ++; compWord.assign(oLine,start,end-start); } if (compWord == word) { found = 1; cout << word << " is in " << oLine << endl; } else inF.getline(oLine,160,'\n'); } }