Start learning free

LESSON 2 OF 69 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool cat v2 in C++: Number Lines (-n) with ostringstream and setw

Practice Read the full explanation

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

    C++ · PROJECTS: COMMAND-LINE TOOLS

    Cat V2 in C++, explained

    Problem overview

    The -n flag of cat puts a line number in front of every line. The function numberedCat takes a vector<string> and returns one string where each row is the 1-based line number, right-aligned in a field 6 characters wide, then a tab character, then the line text. Rows are joined with newlines, with no newline after the last one. The previous version, cat, only joined the lines.

    For ["hello", "world", "foo"] the result is " 1\thello\n 2\tworld\n 3\tfoo". Each number is padded on the left with spaces until it is 6 characters wide. Blank lines are numbered like any other, so ["", "x"] gives " 1\t\n 2\tx". An empty vector gives "".

    Approach: format each row in a string stream

    The structure is the same as in the first version: loop over the positions, put a newline before every row except the first, and append. What is new is the row itself. Building " 1\thello" needs a number padded to a fixed width, which is awkward with plain string operations.

    C++ solves it with stream manipulators. An ostringstream is an output stream that collects what you send into it as text, just as cout sends text to the screen. The manipulator setw(6) sets the minimum width of the next value written to the stream, and by default it pads on the left, which right-aligns numbers. After the row is formatted, oss.str() hands over the text as a string.

    One thing to know about setw: it applies only to the very next value. That suits this lesson, because the number is the only field that needs padding, and the tab and the line text that follow are written at their natural width.

    Step by step

    1. Create an empty string named result. The finished rows are appended to it.
    2. Loop over the positions from 0 while i < lines.size(). The position gives both the line and its number.
    3. Add the separator. When i is above 0, append "\n", so rows are separated and the last row has no newline after it.
    4. Create an ostringstream named oss inside the loop, so each row starts with an empty stream.
    5. Write the row into the stream in order: setw(6), the number i + 1, a "\t", then lines[i]. The number is i + 1 because lines are numbered from 1 while i starts at 0.
    6. Append oss.str() to result. One finished row joins the others.
    7. Return result after the loop.

    The solution in C++

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

    The C++ details worth a closer look:

    • Headers. ostringstream comes from <sstream> and setw from <iomanip>. In the lesson they are already included at the top of the file. In a program of your own you must include both.
    • setw is a minimum. A number wider than 6 digits is not cut: setw(6) with 1234567 prints 1234567, seven characters. It only adds padding when the value is shorter.
    • It affects one value. After setw(6) and a number, the stream goes back to the default width of 0. Writing setw(3) << "x" << setw(6) << 12 produces x 12: each width applies to the single value after it.
    • Why a new stream per row. The stream is declared inside the loop, so every iteration starts with empty text. A stream declared outside would keep growing and str() would return all earlier rows again.
    • The tab is one character. "\t" is a single tab, not spaces. The number takes 6 columns and the tab comes after them.

    Complexity

    Time: O(total length). Each line is visited once. Formatting one number takes time proportional to its digits, which grow only logarithmically with the line count, and the line itself is copied once into the stream and once into result.

    Space: O(total length). The result holds all rows. The stream for the current row is temporary.

    Edge cases and common mistakes

    • Empty vector. The loop doesn't run and the function returns "".
    • Blank lines are numbered. ["", "x"] gives " 1\t\n 2\tx": the first row is the number and a tab with no text after it.
    • Starting at 0. Writing i instead of i + 1 numbers the first line 0.
    • Numbers past 6 digits. A number with more than 6 digits makes that row longer than the others, because setw never truncates.
    • A trailing newline. The separator goes before a row (when i > 0), so the output ends right after the last line's text.
    • Width of the whole row. The 6 columns cover only the number. The tab and the text come after it.

    Testing

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

    • ["hello", "world", "foo"] gives " 1\thello\n 2\tworld\n 3\tfoo".
    • ["", "x"] gives " 1\t\n 2\tx".
    • [] gives "".

    With ten lines that are all "l", the last row is " 10\tl": the number 10 takes two columns and gets four spaces of padding.

    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