#include #include #include #include // This file is incomplete and non-functional; // furthermore, it needs some separation into headers and source files. // It is just a sketch of how to approach the task. // class that contains the program state class Stats { public: Stats() : // initialize members... sum_(0), count_r_(0) { // do not "initialize" members here } // regular member function (method) void process_file(const std::string& filename) { std::ifstream file(filename); std::string line; while (std::getline(file, line)) { std::string_view line_view = line; while (process_word(line_view)) { } } } // static member function (does not depend on instance state) // takes a non-const reference -> modifies the argument static void skip_nonword(std::string_view& line_view) { size_t pos = 0; while (pos < line_view.size() && !std::isalnum(line_view[pos])) { ++pos; } line_view.remove_prefix(pos); } // takes a non-const reference -> modifies the argument bool process_word(std::string_view& line_view) { skip_nonword(line_view); if (line_view.empty()) { return false; } std::size_t pos = 0; while (pos < line_view.size() && std::isalnum(line_view[pos])) { ++pos; } // starting from here, this should be a separate function std::string_view word = line_view.substr(0, pos); if (is_number(word)) { // this should be a separate function for (char c : word) { sum_ += c - '0'; } } else { // this should be a separate function for (char c : word) { if (c == 'r') { ++count_r_; } } // todo: report the word in lowercase } return true; } // takes a copy of `std::string_view` -> does not actually copy the string data // (`std::string_view` is a lightweight "view" of a string similar to a pointer) static bool is_number(std::string_view word) { for (char c : word) { if (!std::isdigit(c)) { return false; } } return true; } private: // data members (state) int sum_; int count_r_; }; void run_program(std::span files) { Stats stats; // create an instance of the class (do not use `new`) for (auto&& file_name : files) { stats.process_file(file_name); // ... } // ... } int main(int argc, char* argv[]) { // starting point of the program std::vector args(argv, argv + argc); }