Start learning free

LESSON 10 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool wc v2 in C++: Count Words (-w) with istringstream

Practice Read the full explanation

Build a tiny version of the Unix wc -w command. Given a list of lines, return the total number of words (whitespace-separated tokens) across all lines as an integer.

Function signature:

int countWords(vector<string> lines)

Example:

Input: lines = ["hello world", "foo bar baz", ""]

Output: 5

The empty string contributes 0 words, "hello world" contributes 2, and "foo bar baz" contributes 3. Total: 5.

Words are separated by one or more spaces or tabs, and leading or trailing whitespace is ignored. A line with no words (empty, or only whitespace) contributes 0, and an empty list of lines gives 0. The input is plain ASCII text.


Use an istringstream for each line and pull tokens with >>. The stream operator skips whitespace automatically and stops at end-of-string.

istringstream ss(lines[i]);
string word;
while (ss >> word) {
    total++;
}


The full solution:
class Solution {
public:
    int countWords(vector<string> lines) {
        int total = 0;
        for (int i = 0; i < lines.size(); i++) {
            istringstream ss(lines[i]);
            string word;
            while (ss >> word) {
                total++;
            }
        }
        return total;
    }
};

STEP 1 OF 7
    Ctrl + Enter to check

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Wc V2 in C++, explained

    Problem overview

    The -w flag of wc counts words. The function countWords takes a vector<string> of lines and returns the total number of words across all of them as an int. A word is a run of characters without whitespace, and words are separated by one or more spaces or tabs. Leading and trailing whitespace is ignored, a line with no words (empty, or only whitespace) adds 0, and an empty vector gives 0.

    For ["hello world", "foo bar baz", ""] the answer is 5: the first line has 2 words, the second has 3 and the empty line has none.

    Approach: let a string stream split the line

    Counting words by hand means tracking whether you are inside a word or between words, with special cases for leading spaces, trailing spaces and runs of several spaces. C++ already has a tool that does this work. An istringstream is an input stream whose text comes from a string instead of the keyboard. Reading from it with >> into a string skips any whitespace in front and then collects characters up to the next whitespace. That is exactly one word.

    The expression ss >> word also gives back the stream itself, and a stream used as a condition is true only while the last read succeeded. When the line has no more words, the read fails and the condition becomes false. So while (ss >> word) runs once per word, and counting inside it counts the words. A blank line, or a line of only spaces and tabs, fails on the first read and adds nothing.

    Tabs need no extra code: the stream treats every whitespace character the same way, so "a\tb" holds two words just like "a b" does.

    Step by step

    1. Create total as an int set to 0. It accumulates the words of all lines, so it must start at zero before any line is read.
    2. Loop over the lines by position with i from 0 while i < lines.size().
    3. Make an istringstream named ss from lines[i]. A fresh stream per line keeps the lines separate: each one is read from its start.
    4. Create an empty string named word. Every successful read stores its word here. The text itself is never used; the variable only gives the read somewhere to put it.
    5. Write while (ss >> word). The loop ends when the line has no words left.
    6. Add 1 to total inside that loop. The body runs once for each word.
    7. Return total after the outer loop. The return sits outside both loops, so it runs once after every line has been counted.

    The solution in C++

    class Solution {
    public:
        int countWords(vector<string> lines) {
            int total = 0;
            for (int i = 0; i < lines.size(); i++) {
                istringstream ss(lines[i]);
                string word;
                while (ss >> word) {
                    total++;
                }
            }
            return total;
        }
    };
    

    The C++ details worth a closer look:

    • The header. istringstream comes from <sstream>. In the lesson it is already included at the top of the file; in a program of your own you add #include <sstream>.
    • Reading into a string stops at whitespace. That is why >> gives words and not whole lines. To read a whole line you would use getline, which is a different tool.
    • The stream in a condition. The loop test is the read itself. Writing a separate check such as while (!ss.eof()) is a common mistake: the end-of-file flag is only set after a read has already failed, so such a loop runs one extra time and counts a word that isn't there.
    • The signed and unsigned comparison. lines.size() is an unsigned type and i is an int. The comparison works for any realistic number of lines, and some compilers warn about it.
    • The vector is passed by value. The signature is fixed by the lesson, so the call copies the vector. A const vector<string>& parameter would avoid the copy, and you will see it often in larger programs.

    Complexity

    Time: O(total length). Each line is copied into a stream once and read once from left to right, so the work is proportional to the number of characters, summed over all lines.

    Space: O(total length) in this version. Beyond the copy of the input made by the by-value parameter, the extra memory is the stream for one line and the word string, which together are proportional to the longest line.

    Edge cases and common mistakes

    • Empty vector. The loop never runs and the function returns 0.
    • Empty and blank lines. [" a \t b ", " "] gives 2: the first line has two words surrounded by extra whitespace, and the second line is only spaces.
    • Counting spaces instead of words. Counting the separators and adding 1 per line gives wrong answers for empty lines, doubled spaces and leading or trailing whitespace. The stream handles all of these without special cases.
    • Tabs. ["a\tb\tc"] gives 3. A tab separates words just as a space does.
    • Reusing one stream for every line. After a stream has failed a read, it stays in the failed state. Creating ss inside the loop gives each line a clean stream.
    • Counting lines. Adding 1 to total once per line instead of once per word gives the number of lines, not words.

    Testing

    • ["hello world", "foo bar baz", ""] gives 5.
    • [" a \t b ", " "] gives 2.
    • ["a\tb\tc"] gives 3.
    • [] gives 0.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free