Video Coming Soon...

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

40: echo

Implement the first command line tool, echo.

View Source file echo.cpp Only

// https://www.gnu.org/software/coreutils/manual/html_node/echo-invocation.html 
//
#include <fmt/core.h>
#include <string>
#include <unistd.h>

int main(int argc, char* argv[]) {
  int opt = 0;
  bool no_newline = false;

  while((opt = getopt(argc, argv, "n")) != -1) {
    switch(opt) {
      case 'n':
        no_newline = true;
        break;
      default:
        fmt::println("USAGE: echo -n [text...]");
        return 1;
    }
  }

  for(int i = optind; i < argc; i++) {
    fmt::print("{} ", argv[i]);
  }

  if(!no_newline) {
    fmt::println("\n");
  }
}
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.