C++ Academy · Lesson

A Word Frequency Counter

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

Lesson 4 of 414 steps

A Word Frequency Counter is a free C++ Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, and your progress syncs across the web and the CoddyKit app. The C++ Academy course includes 4 lessons in total.

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.

Free to start

Learn C++ with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “A Word Frequency Counter” lesson free?

Yes — any 3 lessons of the C++ Academy learning path, including “A Word Frequency Counter”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The C++ Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

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