Skip to content
C++ project #03Beginner

Word Frequency Counter

Analyse any text: word, line and sentence counts, the most frequent meaningful words with bar charts, and stop-word usage.

Estimated time
~2 hours to build
Files
5 files · 259 lines
Technologies
C++17, <map>, <set>, <algorithm>, <cctype>

Introduction

Counting words is the "hello world" of text processing and a perfect excuse to learn std::map. You will normalise messy real-world text (capitals, punctuation, apostrophes), count with a map, then re-sort the results by frequency — the same pattern used in search engines and log analysers.

Problem statement

Read text from standard input until end of file. Normalise each word to lower case, removing surrounding punctuation but keeping inner apostrophes and hyphens. Report the number of lines, sentences, words, unique words, words used only once, the average word length and the longest word, then the ten most frequent words that are not stop words, and the stop words that appeared.

Objectives

  • Count occurrences with std::map<std::string, int>
  • Use std::set for fast membership tests
  • Copy map entries into a vector and sort by a different key
  • Handle characters safely with <cctype>

Features

  • Works on any text piped or typed in
  • Keeps don't and well-known as single words
  • Top-10 list with proportional bar charts, ties broken alphabetically
  • Stop-word list kept separate from the ranking

Concepts demonstrated

  • std::map
  • std::set
  • Structured bindings
  • Custom sort order
  • String normalisation

System architecture

Each line is split on whitespace; every token goes through normalise, which keeps letters and digits (lower-cased) and allows ' or - only after the word has started, then trims them from the end. Words are counted in an ordered std::map, which also gives alphabetical iteration. For the ranking, non-stop-words are copied into a vector<pair<string,int>> and sorted by count descending, then word ascending. Bars are scaled so the most frequent word gets 30 stars.

Folder structure

TextProject tree
word-frequency-counter/
├── README.md
├── Makefile
├── src/main.cpp
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

Makefile

20 lines
MakefileMakefile
# Generated for KENHOLT Skills. Usage: make | make test | make clean
CXX = g++
CXXFLAGS = -std=c++17 -Wall -Wextra -O2
SRC := $(wildcard src/*.cpp)
HDR := $(wildcard src/*.h src/*.hpp)
ARGS := $(shell cat tests/args.txt 2>/dev/null)
INPUT := $(wildcard tests/sample-input.txt)
app: $(SRC) $(HDR)
$(CXX) $(CXXFLAGS) -Isrc $(SRC) -o app
test: app
./app $(ARGS) $(if $(INPUT),< $(INPUT),) > actual.txt
diff actual.txt tests/expected-output.txt && echo "Test passed: output matches tests/expected-output.txt"
clean:
rm -f app app.exe actual.txt
.PHONY: test clean

What each file does

src/main.cpp
The stop-word set, normalise, the counting loop, and the statistics and ranking output in main.
Makefile
Build automation: make builds ./app, make test runs the sample session and compares it with the expected output, make clean removes build files.

How to run it

Build

Terminal
g++ -std=c++17 -Wall -Wextra -Isrc src/*.cpp -o app
# or simply: make

Run

Terminal
./app # Linux / macOS
.\app.exe # Windows

Test against the expected output

Terminal
./app < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt # no output means they match
# Windows PowerShell:
# Get-Content tests\sample-input.txt | .\app.exe > actual.txt
# Compare-Object (Get-Content actual.txt) (Get-Content tests\expected-output.txt)

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Lines : 4
Sentences : 6
Words : 44
Unique words : 31
Used only once : 21
Avg word length : 5.86
Longest word : general-purpose (15 letters)
Top 10 words (stop words excluded)
1. language 3 ******************************
2. practice 3 ******************************
3. because 2 ********************
4. c 2 ********************
5. programming 2 ********************
6. bjarne 1 **********
7. created 1 **********
8. don't 1 **********
9. fast 1 **********
10. general-purpose 1 **********
Stop words used: a(2), and(2), by(1), is(3), it(2), the(2), was(1)
Input
C++ is a general-purpose programming language. It was created by Bjarne Stroustrup.
The language supports procedural, object-oriented and generic programming!
Programmers like C++ because it is fast, and because the standard library is rich.
Don't worry: learning a language takes time. Practice, practice, practice.

Testing

  • Pipe the sample text: ./app < tests/sample-input.txt must match tests/expected-output.txt.
  • Note that 'C++' becomes 'c': punctuation is not part of a word in this program.
  • Run it on a large file (a book from Project Gutenberg) — it should finish instantly.

Common errors

Crash or assertion in isalnum with accented letters

Cast char to unsigned char before calling <cctype> functions, as normalise does.

Nothing happens when typing text

The program reads until end of file: press Ctrl+D (Linux/macOS) or Ctrl+Z then Enter (Windows).

Possible improvements

  • Accept file names on the command line and process several files
  • Let the user choose N for the top-N list
  • Count two-word phrases (bigrams)

Additional challenges

  1. 1Replace std::map with std::unordered_map and sort the output yourself — what changes?
  2. 2Add stemming so 'programming' and 'programmers' count together.
  3. 3Print the words that appear in exactly one line.

Built and tested it yourself? Mark it to update your dashboard.