Video Coming Soon...

Created by Zed A. Shaw Updated 2026-04-18 04:15:27

28: nl

Introduce references here as well.

Implement the first command line tool, nl.

See my first version of nlView Source file nl.cpp Only

// https://www.gnu.org/software/coreutils/manual/html_node/cat-invocation.html

#include <iostream>
#include <fstream>
#include <string>
#include <fmt/core.h>
#include <unistd.h>

void dump_file(std::istream& in) {
  std::string line;
  int line_count = 0;

  while(in) {
    getline(in, line);

    // nl weirdly skips empty lines by default 
    if(line == "") {
      // but still prints it?
      fmt::println("");
      continue;
    } else {
      line_count++;
      fmt::println("{:>6} {}", line_count, line);
    }
  }
}

int main(int argc, char* argv[]) {
  if(argc > 1) {
    // there's files to process
    for(int i = 1; i < argc; i++) {
      std::ifstream in_file{argv[i]};
      dump_file(in_file);
    }
  } else {
    dump_file(std::cin);
  }
}

Previous Lesson Next Lesson

Register for Learn C++ the Hard Way

Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.