// ********************************************************** // // WordLetterCount.cpp // // This program counts the number of words and the number // of occurrences of each letter in a line of input. // // ********************************************************** #include #include using namespace std; void readAndCount (int &numWords, int letterCount[]); // Reads a line of input. Counts the words and the number // of occurrences of each letter. void outputLetterCounts (int letterCount[]); // Prints the number of occurrences of each letter that // appears in the input line. // ========================= // main function // ========================= int main() { int numWords; int letterCount[26]; // stores the frequency of each letter cout << endl; cout << "Enter a line of text.." << endl << endl; readAndCount (numWords, letterCount); cout << endl; cout << numWords << " words" << endl; outputLetterCounts(letterCount); return 0; } // ========================= // Function Definitions // ========================= void readAndCount (int &numWords, int letterCount[]) { bool inAword; // true if current char part of a word char ch; numWords = 0; for ( int i = 0; i < 26; i++ ) letterCount[i] = 0; // initialize array contents to 0 inAword = false; cin.get(ch); while ( ch != '\n') { if ( isalpha(ch) ) { ch = tolower(ch); letterCount[ch - 'a']++; // increments array index ASCII letter value by 1 inAword = true; } else { if (inAword) numWords++; inAword = false; } cin.get(ch); } // count last word if (inAword) numWords++; } void outputLetterCounts(int letterCount[]) { for (int i = 0; i < 26; i++) { if (letterCount[i] > 0) { cout << letterCount[i] << " " << char('a' + i) << endl; } } }