From 1947df9f5f394c0df7941fc751f818e71fe84a5a Mon Sep 17 00:00:00 2001 From: Maxim_Kovalko Date: Tue, 12 May 2026 20:03:02 +0300 Subject: [PATCH] Homework 3 is done! check input.txt, there is some fun dialogue --- .../input.txt | 9 + .../main.cpp | 169 ++++++++++++++++++ .../output.txt | 53 ++++++ 3 files changed, 231 insertions(+) create mode 100644 Kovalko Maxim - Homework 3 - Variant 1/input.txt create mode 100644 Kovalko Maxim - Homework 3 - Variant 1/main.cpp create mode 100644 Kovalko Maxim - Homework 3 - Variant 1/output.txt diff --git a/Kovalko Maxim - Homework 3 - Variant 1/input.txt b/Kovalko Maxim - Homework 3 - Variant 1/input.txt new file mode 100644 index 00000000..239da690 --- /dev/null +++ b/Kovalko Maxim - Homework 3 - Variant 1/input.txt @@ -0,0 +1,9 @@ +Do you know what they call a quarter pounder with cheese in France? +They don't call it a quarter pounder with cheese? +No, they got the metric system, they wouldn't know what the fuck a quarter pounder is +So what they call it? +Royale with cheese +Royale with cheese? What they call a Big Mac? +Bg Mac's a Big Mac but they call it Le Big Mac +Le Big Maque! Hahahahah! What they call a whopper? +I dunno, I didn't go into Burger King diff --git a/Kovalko Maxim - Homework 3 - Variant 1/main.cpp b/Kovalko Maxim - Homework 3 - Variant 1/main.cpp new file mode 100644 index 00000000..fb005303 --- /dev/null +++ b/Kovalko Maxim - Homework 3 - Variant 1/main.cpp @@ -0,0 +1,169 @@ +#include +#include +#include +#include +#include +#include +#include + +void PrintVectorOfStrings(const std::string& title, + const std::vector& vec, + std::ofstream& output_file) { + output_file << "\n--- " << title << " ---\n"; + if (vec.empty()) { + output_file << "(Вектор пуст)\n"; + return; + } + for (size_t i = 0; i < vec.size(); ++i) { + output_file << "[" << i + 1 << "] " << vec[i] << "\n"; + } +} + +void PrintVectorOfInts(const std::string& title, const std::vector& vec, + std::ofstream& output_file) { + output_file << "\n--- " << title << " ---\n"; + if (vec.empty()) { + output_file << "(Вектор пуст)\n"; + return; + } + for (size_t i = 0; i < vec.size(); ++i) { + output_file << "[" << i + 1 << "] " << vec[i] << "\n"; + } +} + +int main() { + // --- 1. Подготовка файлов и пользовательского ввода --- + const std::string kInputFile = "input.txt"; + const std::string kOutputFile = "output.txt"; + + // Открытие потоков для чтения и записи + std::ifstream input_file(kInputFile); + if (!input_file.is_open()) { + std::cerr << "Ошибка: Не удалось открыть файл " << kInputFile + << ". Убедитесь, что он находится в той же директории." << std::endl; + return 1; + } + + std::ofstream output_file(kOutputFile); + if (!output_file.is_open()) { + std::cerr << "Ошибка: Не удалось создать файл " << kOutputFile << "." + << std::endl; + return 1; + } + + // Считывание всех строк из input.txt в исходный вектор + std::vector initial_lines; + std::string line; + while (std::getline(input_file, line)) { + initial_lines.push_back(line); + } + input_file.close(); + + // Запрос пользовательского ввода + int threshold; + std::cout << "Введите минимальную длину строки для фильтрации: "; + std::cin >> threshold; + std::cin.ignore(); // Очистка буфера после cin >> int + + std::string search_word; + std::cout << "Введите слово для поиска (например, 'fun'): "; + std::getline(std::cin, search_word); + + std::vector filtered_lines; + std::cout << "\n[INFO] Фильтрация строк... (Минимум " << threshold + << " символов)" << std::endl; + + // Использование std::copy_if с лямбдой. + // Захват `[threshold]` происходит по значению, что соответствует заданию. + std::copy_if(initial_lines.begin(), initial_lines.end(), + std::back_inserter(filtered_lines), + [threshold](const std::string& s) { + return s.length() >= threshold; + }); + + std::vector transformed_lines; + std::cout << "[INFO] Выполнение Варианта 1: Замена пробелов..." << std::endl; + + for (const std::string& s : filtered_lines) { + std::string new_s = s; + size_t pos = 0; + while ((pos = new_s.find(' ', pos)) != std::string::npos) { + new_s.replace(pos, 1, "_"); + pos += 1; // Перемещаемся на один символ дальше для избежания бесконечного цикла + } + transformed_lines.push_back(new_s); + } + + std::string search_result; + + auto found = std::any_of( + filtered_lines.begin(), filtered_lines.end(), + [&search_word](const std::string& s) { + return s.find(search_word) != std::string::npos; + }); + + if (found) { + search_result = "В векторе найдена хотя бы одна строка, содержащая слово \"" + + search_word + "\"."; + } else { + search_result = "Слово \"" + search_word + "\" не найдено ни в одной строке."; + } + + long long total_char_count = 0; + // Используем std::accumulate. Лямбда подсчитывает символы, кроме '_' + total_char_count = std::accumulate( + filtered_lines.begin(), filtered_lines.end(), 0LL, + [&](long long current_sum, const std::string& s) { + long long count = 0; + for (char c : s) { + if (c != '_') { + count++; + } + } + return current_sum + count; + }); + + std::vector length_vector; + + // Используем std::transform для создания нового вектора из длин элементов + std::transform(filtered_lines.begin(), filtered_lines.end(), + std::back_inserter(length_vector), + [](const std::string& s) { + return static_cast(s.length()); + }); + + output_file << "========================================================\n"; + output_file << " Результаты обработки\n"; + output_file << "========================================================\n"; + + // 1. Исходный вектор строк + PrintVectorOfStrings("Исходный Вектор Строк", initial_lines, output_file); + + // 2. Вектор после удаления коротких строк + PrintVectorOfStrings( + "Вектор После Фильтрации (Длина >= " + std::to_string(threshold) + ")", + filtered_lines, output_file); + + // 3. Вектор после замены пробелов на "_" (Вариант 1) + PrintVectorOfStrings( + "Финальный Вектор После Трансформации (Пробел -> _)", + transformed_lines, output_file); + + // 4. Результат поиска слова + output_file << "\n--- Результат Поиска Слова ---\n"; + output_file << search_result << "\n"; + + // 5. Общее количество символов без "_" + output_file << "\n========================================================\n"; + output_file << "Общее количество символов во всех строках (без учета '_'): " + << total_char_count << "\n"; + + // 6. Вектор длин строк + PrintVectorOfInts("Вектор Длин Строк", length_vector, output_file); + + std::cout << "\n========================================================\n"; + std::cout << "Обработка завершена успешно!\n"; + std::cout << "Все результаты записаны в файл: " << kOutputFile << std::endl; + + return 0; +} diff --git a/Kovalko Maxim - Homework 3 - Variant 1/output.txt b/Kovalko Maxim - Homework 3 - Variant 1/output.txt new file mode 100644 index 00000000..8ffd399a --- /dev/null +++ b/Kovalko Maxim - Homework 3 - Variant 1/output.txt @@ -0,0 +1,53 @@ +======================================================== + Результаты обработки +======================================================== + +--- Исходный Вектор Строк --- +[1] Do you know what they call a quarter pounder with cheese in France? +[2] They don't call it a quarter pounder with cheese? +[3] No, they got the metric system, they wouldn't know what the fuck a quarter pounder is +[4] So what they call it? +[5] Royale with cheese +[6] Royale with cheese? What they call a Big Mac? +[7] Bg Mac's a Big Mac but they call it Le Big Mac +[8] Le Big Maque! Hahahahah! What they call a whopper? +[9] I dunno, I didn't go into Burger King + +--- Вектор После Фильтрации (Длина >= 1) --- +[1] Do you know what they call a quarter pounder with cheese in France? +[2] They don't call it a quarter pounder with cheese? +[3] No, they got the metric system, they wouldn't know what the fuck a quarter pounder is +[4] So what they call it? +[5] Royale with cheese +[6] Royale with cheese? What they call a Big Mac? +[7] Bg Mac's a Big Mac but they call it Le Big Mac +[8] Le Big Maque! Hahahahah! What they call a whopper? +[9] I dunno, I didn't go into Burger King + +--- Финальный Вектор После Трансформации (Пробел -> _) --- +[1] Do_you_know_what_they_call_a_quarter_pounder_with_cheese_in_France? +[2] They_don't_call_it_a_quarter_pounder_with_cheese? +[3] No,_they_got_the_metric_system,_they_wouldn't_know_what_the_fuck_a_quarter_pounder_is +[4] So_what_they_call_it? +[5] Royale_with_cheese +[6] Royale_with_cheese?_What_they_call_a_Big_Mac? +[7] Bg_Mac's_a_Big_Mac_but_they_call_it_Le_Big_Mac +[8] Le_Big_Maque!_Hahahahah!_What_they_call_a_whopper? +[9] I_dunno,_I_didn't_go_into_Burger_King + +--- Результат Поиска Слова --- +В векторе найдена хотя бы одна строка, содержащая слово "cheese". + +======================================================== +Общее количество символов во всех строках (без учета '_'): 418 + +--- Вектор Длин Строк --- +[1] 67 +[2] 49 +[3] 85 +[4] 21 +[5] 18 +[6] 45 +[7] 46 +[8] 50 +[9] 37