C bootcamp · Lab 17

Count the words

mediumStrings12 minLesson: Strings

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read one line of text and print how many words it contains.

A word is a run of non-space characters. Count the transitions from "space" into "a word", so double spaces do not inflate the count.

Input. One line of text.

Output. One integer: the word count.

Examples

Example 1
Input
the quick brown fox
Output
4
Example 2 — Extra spaces do not add phantom words.
Input
hello   world
Output
2
Hint
  1. Read characters with getchar() until newline or EOF.
  2. Keep an "in a word" flag; increment the count each time you enter a word from whitespace.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <stdio.h>
#include <ctype.h>

int main(void) {
  int c, in = 0, count = 0;
  while ((c = getchar()) != EOF) {
    if (c == '\n') break;
    if (isspace(c)) in = 0;
    else if (!in) { in = 1; count++; }
  }
  printf("%d\n", count);
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.