Codiqo

Learn C++ · lesson 33 of 61 · about 10 minutes

Project: Word Counter

Read the scroll at the top of the tower: clean its words, count them, and print the top three.

What you'll learn

  • Read words with std::cin
  • Clean words with tolower and isalpha
  • Sort map entries by count

The scroll in the tower

At the top of the last tower lies an old scroll, and the words that come up most hold its secret. The hero reads it word by word until done. A function above main, clean, keeps only the letters of each word in lower case, so The and WAKES! count as the and wakes. A map counts the clean words, and the top three are found by copying the map into a vector of pairs and sorting it by count.

The plan

1. Read word by word with std::cin >> word
2. Clean each word: keep letters only, lowercase them
3. Count with a map
4. Copy the pairs into a vector and sort by count (highest first, ties alphabetically)

The word counter

#include <algorithm>
#include <cctype>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>

std::string clean(const std::string& raw) {
    std::string out;
    for (char c : raw) {
        if (std::isalpha(static_cast<unsigned char>(c))) out += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
    }
    return out;
}

int main() {
    std::map<std::string, int> counts;
    std::string raw;
    int total = 0;
    while (std::cin >> raw) {
        std::string w = clean(raw);
        if (w.empty()) continue;
        counts[w]++;
        total++;
    }
    std::vector<std::pair<std::string, int>> ranked(counts.begin(), counts.end());
    std::sort(ranked.begin(), ranked.end(), [](const auto& a, const auto& b) {
        return a.second != b.second ? a.second > b.second : a.first < b.first;
    });
    std::cout << total << " words, " << counts.size() << " different\n";
    for (std::size_t i = 0; i < 3 && i < ranked.size(); i++) {
        std::cout << ranked[i].first << ": " << ranked[i].second << "\n";
    }
}

Output

10 words, 6 different
cat: 3
a: 2
the: 2

Tip

Cast to unsigned char before calling isalpha or tolower. Passing a negative char value to them is undefined behaviour.

Tip

The [](const auto& a, const auto& b) { ... } inside std::sort is a lambda: a small function written right where it's needed. It returns true when a should come before b.

Now try it yourself

This lesson is free in Codiqo, with 7 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.