Counting Words and Identifying the Longest Word in C++

BookStats.cpp #include #include #include #include using namespace std; int getIndex(string word, string* words){ for (int i = 0; i < 100; i++){ if (word.compare(words[i]) == 0){ return i; } } return -1; } void tolower(string &word){ for (int i = 0; i < word.size(); i++){ word[i] = tolower(word[i]); } } string removeTrailingPunc(string word){ int i,j; for (i = 0; i < word.size(); i++){ if (!ispunct(word[i])){ break; } } for (j = word.size() - 1; j >= 0; j--){ if (!ispunct(word[j])){ break; } } if (i <= j){ return word.substr(i, j - i + 1); } else{ return ""; } } void printMenu(){ cout << "1- Apology" << endl; cout << "2- Modest Proposal" << endl; cout << "3- Tom Sawyer" << endl; cout << "4- Wizard of OZ" << endl; cout << "5- Exit" << endl; cout << "Please Enter your choice: "; } void readArray(string * words){ int count = 0; string word; ifstream input("100Words_W.txt"); while (input >> word){ words[count++] = word; } input.close(); } int main(){ // Initialize program variables and arrays string words[100]; int wordsCount[100]; double wordsFreqs[100]; string shortest,longest; int totalWordCount; int choice; // menu choice string files[] = {"Apology_W.txt","ModestProposal_W.txt","TomSawyer_W.txt","WizardOfOz_W.txt"}; string inWord; // read word from file int index; int sizesArray[30]; readArray(words); while (1){ // 0- Initialize all the counts to zeros memset(wordsCount, 0, 100 * sizeof(int)); memset(wordsFreqs, 0, 100 * sizeof(double)); memset(sizesArray,0,30 * sizeof(int)); shortest = "abcdefghijklmnopqrstuvwxyz"; longest = ""; totalWordCount = 0; // 1- get choice do{ printMenu(); cin >> choice; } while (choice < 0 || choice > 5); if (choice == 5){ return 0; } // 2- open the file ifstream input(files[choice - 1]); while (input >> inWord){ inWord = removeTrailingPunc(inWord); if (inWord.size() <= 0){ continue; } tolower(inWord); totalWordCount++; if (inWord.size() < shortest.size()){ shortest = inWord; } if (inWord.size() > longest.size()){ longest = inWord; } index = getIndex(inWord, words); if (index != -1){ wordsCount[index]++; } if (inWord.size()<=29 && inWord.size()>0) sizesArray[inWord.size()]++; } input.close(); for (int i = 0; i < 100; i++){ wordsFreqs[i] = wordsCount[i] / (double)totalWordCount; } cout << endl; cout << "Name of the file: " << files[choice - 1] << endl; cout << "Shortest word: " << shortest << endl; cout << "Longest word: " << longest << endl; cout << "Total words count: " << totalWordCount << endl; cout << endl; cout << "100 Word Table:" << endl; cout << "WORD ,COUNT ,FREQ" << endl; for (int i = 0; i < 100; i++){ printf("%-8s,%-8d,%.4f\n", words[i].c_str(), wordsCount[i], wordsFreqs[i]); } cout << "Sizes array:"<