Start learning free

LESSON 1 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool cat v1 in C++: Print Lines with a Newline Join

Practice Read the full explanation

Build a tiny version of the Unix cat command. Given a list of lines, return them joined by newline characters (\n) so they print one per line.

Lines can be blank, and the list can be empty (the result is then an empty string).

Function signature:

string cat(vector<string> lines)

Example:

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

Output: "hello\nworld\nfoo"

When printed:
hello
world
foo

C++'s standard library has no built-in join, so you'll build the result manually. Walk through the lines and accumulate them into a single string, inserting a "\n" between every pair.

A clean trick: only prepend "\n" when i > 0. That way the first line has no separator before it, and every subsequent line is preceded by exactly one newline.
string result;
for (int i = 0; i < lines.size(); i++) {
    if (i > 0) result += "\n";
    result += lines[i];
}


The full solution:
class Solution {
public:
    string cat(vector<string> lines) {
        string result;
        for (int i = 0; i < lines.size(); i++) {
            if (i > 0) result += "\n";
            result += lines[i];
        }
        return result;
    }
};

STEP 1 OF 5
    Ctrl + Enter to check

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Cat V1 in C++, explained

    Problem overview

    The Unix cat command prints text line by line. This first version of the tool is a function, cat, that takes a vector<string> of lines and returns one string in which the lines are separated by newline characters. Printing that string shows one line per row.

    For ["hello", "world", "foo"] the result is "hello\nworld\nfoo". The newlines sit between the lines: there is none after foo. Blank lines are real lines, so ["a", "", "b"] gives "a\n\nb", and an empty vector gives the empty string.

    Approach: add a separator before every line except the first

    C++ has no standard join function for strings, so the result is built by hand: start with an empty string and append to it. The only decision is where the separators go. If every line were followed by "\n", the result would end with an extra newline. If every line were preceded by one, it would start with one.

    The fix is to put a newline before each line except the first. Counting lines by position makes that easy: when the position i is above 0, something has already been written, so a separator is needed first.

    Later versions of the tool build on this function, so the pattern "separator before every item but the first" is worth keeping in mind.

    Step by step

    1. Create an empty string named result. Every line is appended to it, and it is what the function returns.
    2. Loop over the positions with an int counter i from 0 while i < lines.size(). The position is needed, not only the line, because the first line is treated differently.
    3. Add the separator. A one-line if (i > 0) appends "\n". On the first pass nothing is appended.
    4. Append the line: result += lines[i]. An empty line appends nothing, but its separator was already added, which is how blank lines survive.
    5. Return result after the loop. It must sit outside the braces, or the function would return after the first line.

    The solution in C++

    class Solution {
    public:
        string cat(vector<string> lines) {
            string result;
            for (int i = 0; i < lines.size(); i++) {
                if (i > 0) result += "\n";
                result += lines[i];
            }
            return result;
        }
    };
    

    The C++ details worth a closer look:

    • Strings start empty. string result; already holds the empty string, with no initial value needed.
    • += appends in place. It works with both a string literal ("\n") and another string (lines[i]). In a string literal, \n is a single newline character.
    • size() is unsigned. Comparing it with the int i is fine here and the code compiles, although some compilers warn about the mixed signs. It would become a problem if you subtracted from it: lines.size() - 1 on an empty vector wraps around to a huge number instead of becoming -1.
    • The vector is passed by value. The function receives a copy of the lines. For this lesson that is fine. For large inputs, a const vector<string>& parameter avoids the copy, but the lesson's signature uses the plain vector.

    Complexity

    Time: O(total length). The loop visits each line once, and appending a line costs time proportional to its length. Appending to a string takes amortized constant time per character, because the string grows its buffer geometrically.

    Space: O(total length). The result holds every character of every line, plus one newline per gap.

    Edge cases and common mistakes

    • Empty vector. The loop doesn't run, and the function returns "".
    • One line. ["solo"] gives "solo", with no newline, because i is never above 0.
    • A vector holding only an empty string. [""] gives "": one line, and it is empty. Two empty strings give "\n", and three give "\n\n".
    • A trailing newline. Adding "\n" after every line would turn "hello\nworld\nfoo" into "hello\nworld\nfoo\n", which does not match the expected output.
    • Returning inside the loop. A return result; placed before the loop's closing brace stops after the first line.

    Testing

    Each result below is the function's output with newlines written as \n:

    • ["hello", "world", "foo"] gives "hello\nworld\nfoo".
    • ["a", "", "b"] gives "a\n\nb".
    • ["solo"] gives "solo".
    • ["", "", ""] gives "\n\n".
    • [] gives "".
    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