Start learning free

LESSON 371 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: cat v4 — Concatenate Multiple Files in C++

Practice

The real cat command can take many files as arguments and prints them one after another. Build that behavior. Given a list of "files" where each file is itself a list of lines, flatten all lines in order and join them with newlines.

A file can be empty (it adds no lines), and the list can hold no files at all; the result is then an empty string.

Function signature:

string concatCat(vector<vector<string>> allLines)

Example:

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

Output: "hello\nworld\nfoo\nbar\nbaz"

When printed:
hello
world
foo
bar
baz

Use a nested loop. Track whether you've emitted at least one line so you only insert "\n" between lines, never before the first.

A bool first = true; flag works well — set it to false after the first append, and only prepend the newline when !first.
if (!first) result += "\n";
result += allLines[i][j];
first = false;


The full solution:
class Solution {
public:
    string concatCat(vector<vector<string>> allLines) {
        string result;
        bool first = true;
        for (int i = 0; i < allLines.size(); i++) {
            for (int j = 0; j < allLines[i].size(); j++) {
                if (!first) result += "\n";
                result += allLines[i][j];
                first = false;
            }
        }
        return result;
    }
};

STEP 1 OF 8
    Ctrl + Enter to check

    Cat V4 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