Start learning free

LESSON 4 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool cat v4 in C++: Concatenate Several Files with Nested Loops

Practice Read the full explanation

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

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Cat V4 in C++, explained

    Problem overview

    The real cat accepts many files and prints them one after another. In this version, the function concatCat takes a vector<vector<string>> named allLines. Each inner vector is one "file", a list of lines. The function returns all lines, in order, as one string joined with newlines and with none after the last line.

    For [["hello", "world"], ["foo", "bar", "baz"]] the result is "hello\nworld\nfoo\nbar\nbaz". A file can be empty and contributes no lines, so [["a"], [], ["b"]] gives "a\nb". With no files at all, or only empty ones, the result is "".

    Approach: flatten with two loops and a flag

    The task is to flatten a vector of vectors into a single sequence of lines and join it. Two nested loops do the flattening: the outer one visits each file, and the inner one visits each line of that file.

    The separator rule needs more care than in the earlier versions. Before, "add a newline when i > 0" worked because the first line was always at position 0. Here the first line might be in the second or third file, if the files before it are empty, so no loop counter reliably identifies it. For [[], ["a"]], the first line sits at i = 1, and a rule based on i would put a newline in front of a.

    The fix is a bool flag, first, that starts as true and is set to false as soon as one line has been written. It answers the question the separator rule really asks: has anything been written yet?

    Step by step

    1. Create an empty string named result. All lines go into it.
    2. Create bool first = true. It remembers that no line has been written yet.
    3. Loop over the files with i from 0 while i < allLines.size(). Here allLines[i] is one file, a vector<string>.
    4. Loop over the lines of that file with j from 0 while j < allLines[i].size(). For an empty file, this loop runs zero times.
    5. Add the separator. In the inner loop, when first is false, append "\n". The very first line of everything gets no newline in front of it.
    6. Append the line allLines[i][j], which is line j of file i.
    7. Set first to false as the last statement of the inner loop. From now on, every line gets a newline in front of it.
    8. Return result after both loops.

    The solution in C++

    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;
        }
    };
    

    The C++ details worth a closer look:

    • Vectors of vectors. allLines[i] is a vector<string> and allLines[i][j] is a string. The two index operators chain from left to right. Each inner vector can have its own length, so allLines[i].size() is recalculated for each file.
    • >> in templates. The closing >> in vector<vector<string>> is parsed correctly since C++11. Older compilers needed a space between the two brackets.
    • !first. The ! operator flips a bool, so if (!first) reads "if this is not the first line".
    • The flag changes inside the inner loop. It is set to false after the first line is appended, wherever that line is. The flag lives outside both loops so that it keeps its value when the outer loop moves on to the next file.
    • Copy by value. The parameter is a copy of all the lines. A const vector<vector<string>>& would avoid the copy, but the lesson's signature takes the plain value.

    Complexity

    Let F be the number of files and L the total number of characters in all lines.

    Time: O(F + L). The outer loop runs F times, even for empty files. The inner loops together visit every line once, and appending a line costs time proportional to its length.

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

    Edge cases and common mistakes

    • No files. [] gives "", because neither loop runs.
    • Only empty files. [[], []] also gives "".
    • An empty file first. [[], ["a"]] gives "a" with no leading newline. This is the case that breaks a rule based on the loop counters.
    • An empty file in the middle. [["a"], [], ["b"]] gives "a\nb": the empty file adds neither a line nor a newline.
    • Empty strings are lines. [[""], [""]] gives "\n": two blank lines, separated by one newline. A file that holds an empty string is different from an empty file.
    • Setting first = false in the wrong place. If it is set after the loops, or before the line is appended, the separators come out wrong.
    • Declaring first inside the outer loop. It would reset to true for every file, and the files would be glued together with no newline between them.

    Testing

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

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