Count Words
Word counting practices state transitions while scanning text.
What is Count Words?
Word counting practices state transitions while scanning text.
Count whitespace-separated words in a sentence.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
C and C++ code examples
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);
}
words=4
C++
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';
}
words=4
C and C++ comparison
Count a word when a non-space character follows either the beginning or a space.
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.