Source File: wc.cpp

#include <fmt/core.h>
#include <filesystem>
#include <fstream>
#include <string>
#include <cctype>


int count_words(const std::string& buffer) {
  int words = 0;
  bool eat_space = false;
  // buffer.append("\n");   // this fails because const

  for(size_t i = 0; i < buffer.size(); i++) {
    if(isspace(buffer[i])) {
      if(!eat_space) {
        words++;
        eat_space = true;
      }
    } else {
      eat_space = false;
    }
  }

  return words;
}

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 += count_words(buffer);
  }

  fmt::println("lines: {}, words: {}, chars: {}", line_count - 1, word_count, char_count - 1);
}