Beginner C/C++ Exercises

Count Words in a Sentence in C and C++

Count words by spotting where each one starts, even with several spaces between them.

  • Beginner
  • 2 min read
  • 2 runnable examples
What you'll learn
  • Scanning text character by character
  • Tracking whether you are inside a word
  • std::istringstream in C++
"we love C code"
we1
␣␣space
love2
␣space
C3
␣space
code4
Each highlighted start adds one: words = 4.

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.

From sailing past islands to code
isspace(...)🌊 In the water: a space
inside = 0⛵ Not on an island
else if (!inside)🏝️ Just reached land
++words✏️ Count the new island
Count transitions from space into a word.
In one sentence

Counting words means scanning text and adding 1 each time a non-space character follows a space or the start of the text.

Important points

  1. inside remembers whether the previous character was part of a word.
  2. isspace detects spaces, tabs and newlines and sets inside to 0.
  3. A non-space character when inside is 0 starts a new word, so words increases.
  4. "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::istringstream and >> counts words easily.

C and C++ code examples

C
Run code →
main.c
#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);
}
Get a Run button for this example Result of running the code
words=4
C++
Run code →
main.cpp
#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';
}
Get a Run button for this example Result of running the code
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

C exposes small procedural APIs and makes representation details explicit.

C++

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.

Problem
if (*text == ' ') ++words;
Fix
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