C++ bootcamp · Lab 12

Count the words

mediumStrings10 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.

Reading with a std::istringstream and >> naturally skips runs of whitespace, so double spaces do not create empty words.

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 the whole line first: std::getline(std::cin, line);
  2. Feed it to std::istringstream and count how many times >> succeeds.
Show correct code

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

#include <iostream>
#include <sstream>
#include <string>

int main() {
  std::string line;
  std::getline(std::cin, line);
  std::istringstream ss(line);
  std::string word;
  int count = 0;
  while (ss >> word) count++;
  std::cout << count << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.