Not logged in. Log in with GitHub. About Websheets.

List of all available Websheets


Viewing cpp/sstreams/wordcount by redekopp@usc.edu. You have unsaved changes. Log in above to create, edit, preview and publish Websheets.
PropertyValue
Description
html markup
shown to student
 
Write a program that takes any number of lines from input, 
and counts the number of words per line, writing each number on a line 
by itself. For example, for the input
<pre>
Measuring programming progress
by lines of code
is like measuring aircraft building progress
by weight
</pre>
the output should be
<pre>
3
4
6
2
</pre>
Use an <tt>istringstream</tt> with <tt>&gt;&gt;</tt> to skip whitespace.
Public permissions remove
Engine
Template / Reference solution
 
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;
int main() {
   string line;
   // read each line
   while (getline(cin, line)) {
      // create stringstream from line
      stringstream \[storage(line)]\;
      // loop through storage with >>, counting words
\[
      string word;
      int count = 0;
      while (storage >> word) {
         count++;
      }
]\
      // print word count
      cout << \[count]\ << endl;
   }
}
C++ test suite
json list of stdin/args tests
e.g. [{"stdin":"hi", "args":["4", "5"]},
{"stdin":"noargs"}]

to just run once with no input use [{}]
 
[
   {"stdin": "Measuring programming progress\nby lines of code\nis like measuring aircraft building progress\nby weight"},
   {"stdin": "\nThere are only  two  kinds of programming languages\nthose people always gripe about\nand those nobody uses\n"},
   {"stdin": "Weeks of programming can save you hours of planning"}
]
Solution visibility remove


Optional properties:

Note: problems are open-source by default (see 'Public permissions'). Assumed license for open problems is Creative Commons 4.0 Attribution-ShareAlike unless specified in 'Remarks'.