Write a program that will read in a line of text and output the number of
words in the line and the number of occurrences of each letter. Define a
word to be any string of letters that is delimited at each end by either
whitespace, a period, a comma, or the beginning or end of the line. You
can assume that the input consists entirely of letters, whitespace, commas,
and periods. When outputting the number of letters that occur in a line,
be sure to count upper- and lowercase versions of a letter as the same letter.
Output the letters in alphabetical order and list only those letters that
do occur in the input line. For example, the input line
I say Hi.
should produce output similar to the following:
3 words
1 a
1 h
2 i
1 s
1 y
PROGRAM CODE:
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <algorithm>
using namespace std;
int main() {
string line;
cout << "Enter a line of text: ";
getline(cin, line);
istringstream iss(line);
string word;
int wordCount = 0;
unordered_map<char, int> letterCounts;
// Count the number of words
while (iss >> word) {
wordCount++;
}
// Count the occurrences of each letter
for (char c : line) {
if (isalpha(c)) {
c = tolower(c);
letterCounts[c]++;
}
}
// Output the number of words
cout << wordCount << " words" << endl;
// Output the number of occurrences of each letter in alphabetical order
for (auto entry : letterCounts) {
cout << entry.second << " " << entry.first << endl;
}
return 0;
}
OUTPUT OF THE PROGRAM CODE:
Enter a line of text: hello Martin
2 words
1 i
1 t
1 n
1 a
1 m
1 o
2 l
1 r
1 e
1 h