Start learning free

LESSON 368 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: cat v1 — Print Lines in C++

Practice

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

    Cat V1 in C++

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free