diff --git a/others/kirill`s/lab1/task18.cpp b/others/kirill`s/lab1/task18.cpp index e1a3eeb..9b71547 100644 --- a/others/kirill`s/lab1/task18.cpp +++ b/others/kirill`s/lab1/task18.cpp @@ -2,6 +2,8 @@ #include #include #include +#include +#include static bool file_exists(const std::string &path) { struct stat st{}; @@ -14,13 +16,30 @@ static std::string make_out_name(const std::string &in) { return in.substr(0, pos) + ".out"; } +static bool parse_nonneg_ll(const char *s, long long &out) { + if (!s || *s == '\0') return false; + char *end = nullptr; + errno = 0; + long long v = std::strtoll(s, &end, 10); + if (errno != 0 || end == s || *end != '\0') return false; + if (v < 0) return false; + out = v; + return true; +} + int main(int argc, char *argv[]) { - if (argc != 2) { - std::cerr << "Usage: " << argv[0] << " \n"; + if (argc != 3) { + std::cerr << "Usage: " << argv[0] << " input_file replace_count\n"; return -1; } std::string in_path = argv[1]; + long long target = 0; + if (!parse_nonneg_ll(argv[2], target)) { + std::cerr << "Usage: " << argv[0] << " input_file replace_count\n"; + return -1; + } + if (!file_exists(in_path)) { std::cerr << "Error: input file does not exist.\n"; return -1; @@ -43,10 +62,10 @@ int main(int argc, char *argv[]) { std::string line; while (std::getline(in, line)) { - if (!line.empty()) { - for (std::size_t idx = 0; idx < line.size(); ++idx) { + if (!line.empty() && replacements < target) { + for (std::size_t idx = 0; idx < line.size() && replacements < target; ++idx) { std::size_t pos1 = idx + 1; - if (pos1 % 3 == 0) { + if ((pos1 % 3) == 0) { if (line[idx] != ' ') { line[idx] = ' '; ++replacements; @@ -62,6 +81,16 @@ int main(int argc, char *argv[]) { } } + if (!in.eof() && in.fail()) { + std::cerr << "Error: read error.\n"; + return -1; + } + + if (replacements != target) { + std::cerr << "Error: could not perform exactly requested replacements.\n"; + return -1; + } + std::cout << replacements << std::endl; - return static_cast(replacements); + return 0; }