#include #include #include using namespace std; const size_t MAX_WORDS{100}; struct WordAndCountT { string word; int count{1}; }; void PrintWordAndCountT (WordAndCountT entry); void PrintDictionary(const WordAndCountT dictionary[], size_t size); string StripWord(string word); size_t FindWord(string word, const WordAndCountT dictionary[], size_t size); int main() { //WordAndCountT dictionary[MAX_WORDS]; WordAndCountT * dictionary{nullptr}; size_t capacity{10}; dictionary = new WordAndCountT[capacity]; size_t entryCount{0}; ifstream inFile("ocap.txt"); string word; size_t pos; inFile >> word; while(inFile) { word = StripWord(word); if (word != "") { pos = FindWord(word, dictionary, entryCount); if (pos == entryCount) { if (entryCount >= capacity) { cout << "Out of space, doubling capacity " << capacity << endl; // allocate more space // copy the data over // delete the old space WordAndCountT * tmpSpace{nullptr}; tmpSpace = new WordAndCountT[capacity*2]; for(size_t i =0; i < capacity; ++i) { tmpSpace[i] = dictionary[i]; } delete[] dictionary; dictionary = tmpSpace; capacity *= 2; } dictionary[entryCount].word = word; ++entryCount; } else { ++dictionary[pos].count; } } //cout << word << endl; inFile >> word; } PrintDictionary(dictionary, entryCount); inFile.close(); delete[] dictionary; return 0; } size_t FindWord(string word, const WordAndCountT dictionary[], size_t size){ size_t i{0}; while (i < size and dictionary[i].word != word) { ++i; } return i; } void PrintDictionary(const WordAndCountT dictionary[], size_t size){ for(size_t i = 0; i < size; ++i) { PrintWordAndCountT(dictionary[i]); } } string StripWord(string word){ string fixedWord; for(size_t i = 0; i < word.size(); ++i) { if (isalpha(word[i]) ) { fixedWord += static_cast(tolower(word[i])); } } return fixedWord; } void PrintWordAndCountT (WordAndCountT entry){ cout << entry.word << " occurs " << entry.count << " times" << endl; }