Video Coming Soon...

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

30: cat

Implement the first command line tool, wc.

View Source file wc.cpp Only

// https://www.gnu.org/software/coreutils/manual/html_node/wc-invocation.html
#include <fmt/core.h>
#include <filesystem>
#include <fstream>
#include <string>
#include <regex>
#include <iterator>


int count_words(const std::string& buffer) {
  std::regex words_regex("([^\\s]+)");

  std::sregex_iterator words_begin(buffer.begin(), buffer.end(), words_regex);
  std::sregex_iterator words_end{};

  return std::distance(words_begin, words_end);
}

int wtf_count_words(const std::string& buffer) {
  std::regex words_regex("([^\\s]+)");
  int word_count = 0;
  std::smatch sm;

  for(auto i = buffer.begin(); i != buffer.end(); i += sm.size() + 1) {
    if(std::regex_search(i, buffer.end(), sm, words_regex)) {
      word_count++;
    } else {
      break;
    }
  }

  return word_count;
}

int size_count_words(const std::string& buffer) {
  std::regex words_regex("([^\\s]+)");
  int word_count = 0;
  std::smatch sm;

  for(size_t i = 0; i < buffer.size(); i += sm.size() + 1) {
    if(std::regex_search(buffer.begin() + i, buffer.end(), sm, words_regex)) {
      word_count++;
    } else {
      break;
    }
  }

  return word_count;
}

int copy_copy_count_words(std::string buffer) {
  std::regex words_regex("([^\\s]+)");
  int word_count = 0;

  for(std::smatch sm; std::regex_search(buffer, sm, words_regex); buffer = sm.suffix()) {
    word_count++;
  }

  return word_count;
}

int main(int argc, char* argv[]) {
  std::filesystem::path file_name{argv[1]};
  std::ifstream in_file{file_name};
  std::string buffer;

  int line_count = 0;
  int word_count = 0;
  int char_count = 0;

  while(in_file) {
    getline(in_file, buffer);
    line_count++;
    char_count += buffer.size() + 1; // one extra for \n
    word_count += copy_copy_count_words(buffer);
  }

  fmt::println("lines: {}, words: {}, chars: {}", line_count - 1, word_count, char_count - 1);
}
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.