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
Input
the quick brown fox
Output
4
Input
hello world
Output
2
Hint
- Read the whole line first: std::getline(std::cin, line);
- 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.