Count Words in a Sentence in C and C++
Count words by spotting where each one starts, even with several spaces between them.
- Scanning text character by character
- Tracking whether you are inside a word
- std::istringstream in C++
Count the start of each word
The problem
Word counts are used in editors, search and text analysis. Counting spaces does not work when words are separated by several spaces, so a better approach counts where words begin.
Think of it like this
Counting words is like counting islands while sailing along a coastline. You count one island each time you go from water onto land, no matter how long the island is or how much water separates them.
isspace(...)🌊 In the water: a spaceinside = 0⛵ Not on an islandelse if (!inside)🏝️ Just reached land++words✏️ Count the new islandCounting words means scanning text and adding 1 each time a non-space character follows a space or the start of the text.
Important points
insideremembers whether the previous character was part of a word.isspacedetects spaces, tabs and newlines and setsinsideto 0.- A non-space character when
insideis 0 starts a new word, sowordsincreases. "C and C++ examples"has 4 words.
When to use it
- Word counters in editors and text tools.
- Practicing state variables while scanning text.
- Tokenizing input into words.
When not to use it
- Punctuation should split words too: add those characters to the separator test.
- C++ code: reading with
std::istringstreamand>>counts words easily.
C and C++ code examples
#include <ctype.h>
#include <stdio.h>
int main(void) {
const char *text = "C and C++ examples"; int words = 0, inside = 0;
// Count transitions from whitespace into a word.
for (; *text; ++text) { if (isspace((unsigned char)*text)) inside = 0; else if (!inside) { ++words; inside = 1; } }
printf("words=%d\n", words);
}
words=4
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::istringstream input("C and C++ examples"); std::string word; int words = 0;
// Formatted extraction skips whitespace and returns one word.
while (input >> word) ++words;
std::cout << "words=" << words << '\n';
}
words=4
C and C++ comparison
inside tracks whether the scan is currently in a word. A space sets it to 0, and the first non-space character after that counts a new word and sets it to 1. Multiple spaces never count twice, and the sentence gives words=4.
C exposes small procedural APIs and makes representation details explicit.
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.
Common mistakes
Counting spaces
Double spaces or leading spaces give the wrong count.
if (*text == ' ') ++words;
if (isspace((unsigned char)*text)) inside = 0;
else if (!inside) { ++words; inside = 1; }
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges