Lesson 17 of 23

nl

The nl Command

nl numbers the lines of its input:

$ printf "apple\nbanana\ncherry\n" | nl
     1	apple
     2	banana
     3	cherry

Each line is prefixed with a right-justified line number in a 6-character field, followed by a tab. The real nl uses %6d\t — our version will match that format by computing the padding manually.

Your Implementation

Write void my_nl(const char *s) that numbers and prints lines.

To right-justify a number in 6 characters:

  1. Count its digits
  2. Print 6 - digits spaces
  3. Print the number with printf("%d\t", n)
void my_nl(const char *s) {
    int n = 1;
    while (*s) {
        // Count digits of n
        int tmp = n, digits = 0;
        do { digits++; tmp /= 10; } while (tmp);
        // Pad to width 6
        for (int i = digits; i < 6; i++) putchar(' ');
        printf("%d\t", n++);
        while (*s && *s != '\n') { putchar(*s); s++; }
        putchar('\n');
        if (*s == '\n') s++;
    }
}

Counting Digits

The do { digits++; tmp /= 10; } while (tmp); loop counts digits by repeatedly dividing by 10. A do…while is used so that 0 is counted as 1 digit.

Your Task

Implement my_nl that prints each line prefixed with its right-justified line number in a 6-character field followed by a tab.

TCC compiler loading...
Loading...
Click "Run" to execute your code.