0Pricing
C++ Academy · Lesson

A Word Frequency Counter

Count occurrences of each word in a text file using std::map.

A Word Frequency Counter is a free C++ Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Project Goal

Read a text file and print each unique word with its occurrence count. A classic problem solved cleanly with std::map or std::unordered_map.

Required Headers

File I/O, strings, and an associative container.

#include <fstream>
#include <map>
#include <string>
#include <iostream>

Reading Words One at a Time

The >> extraction operator reads whitespace-separated tokens — perfect for raw words.

std::ifstream file("book.txt");
std::map<std::string, int> counts;
std::string word;
while (file >> word) {
    counts[word]++;
}

Normalizing Words

Lowercase each word so "Hello" and "hello" count as the same.

#include <algorithm>
std::transform(word.begin(), word.end(), word.begin(),
    [](unsigned char c) { return std::tolower(c); });

Stripping Punctuation

Remove punctuation from the start and end of each word.

while (!word.empty() && !std::isalpha(word.front())) word.erase(0,1);
while (!word.empty() && !std::isalpha(word.back())) word.pop_back();

Printing the Counts

Iterate the map and print each pair. std::map iterates in sorted key order.

for (const auto& [w, n] : counts) {
    std::cout << w << ": " << n << "\n";
}

Sorted by Frequency

To print by frequency instead of alphabetically, copy the entries into a vector and sort it.

std::vector<std::pair<std::string, int>> entries(counts.begin(), counts.end());
std::sort(entries.begin(), entries.end(),
    [](auto& a, auto& b) { return a.second > b.second; });

Top N Most Common

Print only the top 10 (or any N) entries from the sorted vector.

for (size_t i = 0; i < 10 && i < entries.size(); ++i) {
    std::cout << entries[i].first << ": " << entries[i].second << "\n";
}

map vs unordered_map

For large files, std::unordered_map is faster on average (O(1) lookup) but iterates in arbitrary order. Use std::map for sorted output.

Stop Words

Filter out common short words like "the", "and", "of" using a set of stop words.

static const std::set<std::string> stop = {"the","and","of","to","a"};
if (stop.count(word)) continue;

Counting Lines or Characters

Variants of the same pattern: count total lines with std::getline, total characters with std::ifstream + std::istreambuf_iterator.

Performance Considerations

For massive files use unordered_map with string_view keys, mmap the file, and avoid heap allocations per word.

Quick Check

Which container automatically iterates in alphabetical order?

Recap

A word frequency counter pulls together streams, strings, associative containers, and algorithms. Choose map for sorted output or unordered_map for speed. Normalize, strip punctuation, and consider stop words for cleaner results.

Frequently asked questions

Is the “A Word Frequency Counter” lesson free?

Yes — the full text of “A Word Frequency Counter” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.

What will I learn in “A Word Frequency Counter”?

Count occurrences of each word in a text file using std::map. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “A Word Frequency Counter” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Building a Simple Calculator CLI
  2. Reading and Writing CSV Files
  3. A Number Guessing Game
  4. A Word Frequency Counter
← Back to C++ Academy