#include #include #include #include using namespace std; struct WordEntryT { string word; int count; }; const size_t MAX_WORDS = 100; const size_t NOT_FOUND = 99999; void FillArray(WordEntryT words[] , size_t & wordCount, ifstream & inFile); void SortArray(WordEntryT words[], size_t wordCount); void PrintArray(WordEntryT words[], size_t wordCount); size_t Find(WordEntryT words[], size_t wordCount, string key); void Swap(WordEntryT & a, WordEntryT & b); string StripWord(string word); int main() { WordEntryT words[MAX_WORDS]; size_t wordCount = 0; ifstream inFile; inFile.open("charge.txt"); FillArray(words, wordCount, inFile); inFile.close(); SortArray(words, wordCount); PrintArray(words, wordCount); return 0; } string StripWord(string word) { size_t i; string returnWord; for(i=0;i(tolower(word[i])); } } return returnWord; } size_t Find(WordEntryT words[], size_t wordCount, string key) { size_t pos = NOT_FOUND; size_t i = 0; while (i < wordCount and pos == NOT_FOUND) { if (words[i].word == key) { pos = i; } i++; } return pos; } void FillArray(WordEntryT words[] , size_t & wordCount, ifstream & inFile){ string word; size_t pos; WordEntryT entry; inFile >> word; while (inFile) { word = StripWord(word); if (word != "") { pos = Find(words, wordCount, word); if (pos != NOT_FOUND) { words[pos].count ++; } else { if (wordCount < MAX_WORDS) { entry.word = word; entry.count = 1; words[wordCount] = entry; wordCount++; } else { cout << "Error: the array is full, can't add " << word << endl; } } } inFile >> word; } return; } void Swap(WordEntryT & a, WordEntryT & b) { WordEntryT tmp; tmp = a; a = b; b = tmp; return; } void SortArray(WordEntryT words[], size_t wordCount){ size_t i,j; size_t smallPos; for(i =0; i < wordCount; i++) { smallPos = i; for(j = i+1; j < wordCount; j++) { if (words[smallPos].count > words[j].count) { smallPos = j; } } if (smallPos != i) { Swap(words[i], words[smallPos]); } } return; } void PrintArray(WordEntryT words[], size_t wordCount){ size_t i; for(i=0; i < wordCount; i++) { cout << setw(15) << words[i].word << setw(10) << words[i].count << endl; } cout << endl; return; }