SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Strings And Vectors
Exercise:
Programming Projects
Question:2 | ISBN:9780321531346 | Edition: 7

Question

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

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.