Start learning free

LESSON 369 OF 409 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: cat v2 — Number Lines (-n) in C++

Practice

Now build the -n flag of the cat tool, as a new function. It prints every line preceded by its 1-based line number, right-aligned in 6 columns, then a tab character, then the line text. Blank lines are numbered too, and an empty list gives an empty string.

Function signature:

string numberedCat(vector<string> lines)

Format per line: the line number right-aligned in a field 6 characters wide (padded with spaces on the left), then a literal tab (\t), then the original line.

Example:

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

Output:
"     1\thello\n     2\tworld\n     3\tfoo"

When printed:
     1	hello
     2	world
     3	foo

Use an ostringstream with setw(6) to right-justify each number. Loop by index, prepend a "\n" when i > 0, build the formatted prefix, then append the line.

Inside the loop:
ostringstream oss;
oss << setw(6) << (i + 1) << "\t" << lines[i];
result += oss.str();


The full solution:
class Solution {
public:
    string numberedCat(vector<string> lines) {
        string result;
        for (int i = 0; i < lines.size(); i++) {
            if (i > 0) result += "\n";
            ostringstream oss;
            oss << setw(6) << (i + 1) << "\t" << lines[i];
            result += oss.str();
        }
        return result;
    }
};

STEP 1 OF 7
    Ctrl + Enter to check

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