TryBugHunt
cppInfinite loopEasy

Counting a word that appears never finishes

BugFind the bug and fix the code

What it should do

countWord(text, word) counts how many times word appears in text. Example: countWord("the cat and the hat", "the") → 2

What happens instead

countWord("the cat and the hat", "the") never returns and the run times out. countWord("abc", "x") returns 0 straight away.

#include <string>

int countWord(std::string text, std::string word) {
    int count = 0;
    size_t pos = text.find(word);
    while (pos != std::string::npos) {
        count++;
        pos = text.find(word, pos);
    }
    return count;
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the infinite loops pattern

The loop condition never becomes false, so the program runs until it is stopped.

What you'll practise

An easy C++ debugging exercise about infinite loops: the loop condition never becomes false, so the program runs until it is stopped.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

What went wrong: text.find(word, pos) starts searching at pos, and pos is where the word was just found. So it finds the same copy again and again, and pos never changes.

The fix: Start the next search after the match: text.find(word, pos + word.size()).

Remember: In a find loop, each search must start after the previous match. If the loop only hangs when there is a match, the start position is not moving forward.

The pattern behind it: infinite loops.

More infinite loops to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/11c7e2f2-f41d-42cd-a659-28453b50bf82" title="Debugging challenge: Counting a word that appears never finishes" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/11c7e2f2-f41d-42cd-a659-28453b50bf82">TryBugHunt</a></p>