/** wordsInFile.cpp * Separate a file into tokens, and store them individually in an array of string * Print them and output the number of words in the file * * The array used to store the words is partially-filled */ #include #include #include #include using namespace std; /** * Interactively obtain the name of a file to open from the user * Paramater: * source: EXPORT - must be reference * Returns: If true, source is a handle for a file to read * If false, source is a zero-valued stream, i.e. not open */ bool openForRead(ifstream &source); /** * Read the content one token at a time * from the file represented by parameter source, placing the words * into the parameter array words. * Parameter count will hold the number of words in array words. * Parameters: * source: IMPORT/EXPORT * words : EXPORT * count : EXPORT */ void getWords(ifstream &source,string words[],int &count); /** * Print the tokens held in the array * Parameters: * words : IMPORT * count : IMPORT */ void printWords(string words[],int count); // why no & on the int or array? int const MAXWORDS=1000; int main() { string wordList[MAXWORDS]; int numWords; ifstream source; if (!openForRead(source)) { cout << "Open Failed..Check the Data File Name\n"; return(-1); } getWords(source, wordList, numWords); printWords(wordList, numWords); return(0); } // Open a file for reading. If file not opened, return false, else return true bool openForRead(ifstream &source) { string fileName; cout << "Enter File to Read >"; cin >> fileName; source.open(fileName.c_str()); if (source.fail()) return(false); return(true); } // Input a file, separating out each token. Limit is 1000 tokens void getWords(ifstream &source,string words[],int &count) { string Token; count=0; while (!source.eof() && count> Token; words[count++]=Token; } source.close(); } bool openForWrite(ofstream & dest) { string fileName; cout << "Enter Filename for Output >"; cin >> fileName; dest.open(fileName.c_str()); if (!dest) { cout << "Attempt to Open " << fileName << " Failed\n"; dest.close(); return(false); } return(true); } // Output all the words void printWords(string words[],int count) { ofstream dest; bool ok; do { ok=openForWrite(dest); if (!ok) cout << " Destination file couldn't be opened. Try again\n"; } while (!ok); if (count) dest << "Words that Appeared in the File\n"; for (int i=0; i