Start learning free

LESSON 12 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool wc v4 in C++: Choose What to Count with a Mode String

Practice Read the full explanation

Combine the previous three versions of wc. Given a list of lines and a mode flag, return the requested count(s) as a string. This is our own simplified interface, not the real wc flags: the real tool combines flags (such as -lw) and pads its columns with spaces.

Function signature:

string wc(vector<string> lines, string mode)

Mode values:

  • "l" → line count, as a string.
  • "w" → word count (whitespace-separated tokens), as a string.
  • "c" → character count (lines only, no separating newlines), as a string.
  • "all" → lines + "\t" + words + "\t" + chars.

The "c" count is the one from v3 (the sum of the line lengths, no newlines). Any other mode value, for example "x" or "L" (modes are case-sensitive), gives the same result as "all". For an empty list, "l", "w" and "c" give "0" and "all" gives "0<TAB>0<TAB>0". The input is plain ASCII text.

Example:

Input: lines = ["hello", "world"], mode = "all"

Output: "2\t2\t10"

2 lines, 2 words (one per line), 10 characters total.


Compute all three counts upfront. Use istringstream for the word count and .size() for the character count. Branch on the mode string at the end.

int numLines = lines.size();
int numWords = 0;
int numChars = 0;
for (int i = 0; i < lines.size(); i++) {
    istringstream ss(lines[i]);
    string word;
    while (ss >> word) numWords++;
    numChars += lines[i].size();
}
Use to_string(int) to convert numbers to strings.

The full solution:
class Solution {
public:
    string wc(vector<string> lines, string mode) {
        int numLines = lines.size();
        int numWords = 0;
        int numChars = 0;
        for (int i = 0; i < lines.size(); i++) {
            istringstream ss(lines[i]);
            string word;
            while (ss >> word) numWords++;
            numChars += lines[i].size();
        }
        if (mode == "l") return to_string(numLines);
        if (mode == "w") return to_string(numWords);
        if (mode == "c") return to_string(numChars);
        return to_string(numLines) + "\t" + to_string(numWords) + "\t" + to_string(numChars);
    }
};

STEP 1 OF 12
    Ctrl + Enter to check

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Wc V4 in C++, explained

    Problem overview

    This version combines the previous three counters in one function, wc, which takes a vector<string> of lines and a string named mode, and returns the requested count as text. The modes are:

    • "l": the number of lines;
    • "w": the number of words, split on whitespace;
    • "c": the number of characters, the sum of the line lengths with no newlines;
    • "all": the line, word and character counts joined by tab characters.

    Any other mode, such as "x" or "L" (modes are case-sensitive), gives the same result as "all". This is the lesson's own simplified interface, not the flags of the real tool.

    For ["hello", "world"] with mode "all" the result is "2\t2\t10": 2 lines, 2 words and 10 characters. For an empty vector, "l", "w" and "c" each give "0", and "all" gives "0\t0\t0".

    Approach: count everything once, then choose

    Each count is already known from the earlier versions. The simplest way to combine them is to compute all three in a single pass over the lines and decide at the end which one to return. That is cheap, because all three counts are quick to get, and it keeps the loop free of mode checks.

    The line count needs no loop at all: it is the size of the vector. The word count uses an istringstream per line and counts successful reads with >>. The character count adds the size of each line. The two loop-based counts share one loop.

    The choice comes last, as a chain of if statements that each return. The last line is not guarded by any condition. Every mode that is not "l", "w" or "c" reaches it, so "all" and every unknown mode share the same result without a special case.

    Step by step

    1. Store the line count in numLines. It is lines.size(), so no loop is needed for it.
    2. Create numWords as an int set to 0. It grows while the loop reads lines.
    3. Create numChars the same way.
    4. Loop over the lines by position with i from 0 while i < lines.size().
    5. Make an istringstream named ss from lines[i]. It will hand out the line's words one at a time.
    6. Create a string named word to receive each word.
    7. Count the words with a single-statement while (ss >> word) that adds 1 to numWords. A blank line fails the first read and adds nothing.
    8. Add lines[i].size() to numChars before the loop ends. The characters come from the whole line, spaces included.
    9. Return the line count as text for mode "l". The function returns a string, so the int goes through to_string first.
    10. Do the same for "w" with the word count.
    11. And for "c" with the character count.
    12. Return the three counts joined by tabs on the last line, in the order lines, words, characters. Each number goes through to_string, and the pieces are joined with +.

    The solution in C++

    class Solution {
    public:
        string wc(vector<string> lines, string mode) {
            int numLines = lines.size();
            int numWords = 0;
            int numChars = 0;
            for (int i = 0; i < lines.size(); i++) {
                istringstream ss(lines[i]);
                string word;
                while (ss >> word) numWords++;
                numChars += lines[i].size();
            }
            if (mode == "l") return to_string(numLines);
            if (mode == "w") return to_string(numWords);
            if (mode == "c") return to_string(numChars);
            return to_string(numLines) + "\t" + to_string(numWords) + "\t" + to_string(numChars);
        }
    };
    

    The C++ details worth a closer look:

    • to_string converts numbers to text. to_string(42) is "42". You can't add an int to a string with + directly, which is why every number is converted first.
    • Joining with + works on a string and a literal. to_string(numLines) + "\t" is a string plus a character array, which C++ accepts because the left side is already a string. Two plain literals, "a" + "b", would not compile.
    • Comparing strings with ==. For string values, mode == "l" compares the contents, so it works as you would hope. The comparison is exact: "L" is not "l".
    • A braceless while and one-line ifs. A single statement doesn't need braces. The lesson uses that style for the word counter and for the three early returns, and it works only because each body is exactly one statement.
    • Order of the checks. The early returns are independent, so their order among "l", "w" and "c" doesn't matter. The unguarded return has to come last.

    Complexity

    Time: O(total length). The loop reads each line once for the words, and size() takes constant time. Building the answer string is proportional to the number of digits, which is tiny. The by-value vector parameter also costs a copy proportional to the total length.

    Space: O(total length) in this version, mostly from that copy. Besides it, the code uses three integers and the stream for one line.

    Edge cases and common mistakes

    • Empty vector. With an empty vector, mode "l" gives "0" and mode "all" gives "0\t0\t0", because every count starts at 0 and the loop doesn't run.
    • Unknown modes. For ["hello world", "foo bar baz", ""], both "L" and "x" give "3\t5\t22", the same as "all".
    • Returning a number. The function returns text. Writing return numLines; doesn't compile, because an int doesn't convert to a string.
    • The order in "all". It is lines, words, characters, with a tab between each pair and no tab at the end.
    • Counting newlines as characters. The character count is the sum of the line lengths, so ["hello", "world"] has 10 characters, not 11.
    • Blank lines. They count as lines and add 0 words and 0 characters. The empty third line of the example is why there are 3 lines but only 5 words.

    Testing

    Results are the function's return values, with tabs written as \t. With lines = ["hello world", "foo bar baz", ""]:

    • mode "l" gives "3".
    • mode "w" gives "5".
    • mode "c" gives "22".
    • mode "all" gives "3\t5\t22".

    With lines = ["hello", "world"], mode "all" gives "2\t2\t10". With an empty vector, mode "l" 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