/
Sowl
/
Pracktikal06
Обзор
Документация
Войти
/
Sowl
/
Pracktikal06
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
Practical_work_0.cpp
483 строки
13 KB
Sowl
Исправление кодировки. Добавление пунктов в меню.
04 июн 2026, 17:32
04 июн 2026, 17:32
9388a2c
Код
Авторство
О чём код?
#include <iostream> #include <vector> #include <string> #include <fstream> #include <limits> #include <algorithm> #define NOMINMAX #include <windows.h> using namespace std; // Структура товара struct Product { string name; int quantity; double price; double totalPrice; }; // Установка кодировки Windows-1251 для кириллицы void setRussianConsole() { SetConsoleOutputCP(1251); SetConsoleCP(1251); } // Проверка корректного ввода целого числа int inputInt(string message) { int value; while (true) { cout << message; if (cin >> value && value >= 0) { cin.ignore(); return value; } cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Ошибка! Введите корректное число (0 или больше).\n"; } } // Проверка корректного ввода десятичного числа double inputDouble(string message) { double value; while (true) { cout << message; if (cin >> value && value >= 0) { cin.ignore(); return value; } cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "Ошибка! Введите корректное число (0 или больше).\n"; } } // Ввод названия товара string inputString(string message) { string value; cout << message; getline(cin, value); return value; } // Преобразование строки в нижний регистр для поиска (с поддержкой кириллицы) string toLower(string str) { for (char& c : str) { if (c >= 'А' && c <= 'Я') c = c + ('а' - 'А'); else if (c >= 'A' && c <= 'Z') c = c + ('a' - 'A'); } return str; } // Добавление товаров void addProducts(vector<Product>& products) { int n = inputInt("Сколько товаров добавить? "); for (int i = 0; i < n; i++) { Product p; cout << "\nТовар #" << i + 1 << endl; p.name = inputString("Введите название товара: "); p.quantity = inputInt("Введите количество: "); p.price = inputDouble("Введите цену за единицу: "); p.totalPrice = p.quantity * p.price; products.push_back(p); cout << "Товар успешно добавлен!\n"; } } // Вывод всех товаров void showProducts(const vector<Product>& products) { if (products.empty()) { cout << "\nСписок товаров пуст.\n"; return; } double warehouseTotal = 0; cout << "\n===== СПИСОК ТОВАРОВ =====\n"; cout << "------------------------------------------------\n"; for (size_t i = 0; i < products.size(); i++) { cout << "\nТовар #" << i + 1 << endl; cout << " Название: " << products[i].name << endl; cout << " Количество: " << products[i].quantity << endl; cout << " Цена: " << products[i].price << " руб." << endl; cout << " Стоимость: " << products[i].totalPrice << " руб." << endl; warehouseTotal += products[i].totalPrice; } cout << "\n------------------------------------------------\n"; cout << "Общая стоимость склада: " << warehouseTotal << " руб.\n"; } // Поиск товара по названию void searchProduct(const vector<Product>& products) { if (products.empty()) { cout << "\nСписок товаров пуст.\n"; return; } string searchName = inputString("\nВведите название товара для поиска: "); bool found = false; string searchLower = toLower(searchName); cout << "\n===== РЕЗУЛЬТАТЫ ПОИСКА =====\n"; for (const auto& p : products) { string nameLower = toLower(p.name); if (nameLower.find(searchLower) != string::npos) { cout << "\nТовар найден:" << endl; cout << " Название: " << p.name << endl; cout << " Количество: " << p.quantity << endl; cout << " Цена: " << p.price << " руб." << endl; cout << " Стоимость: " << p.totalPrice << " руб." << endl; found = true; } } if (!found) { cout << "Товар \"" << searchName << "\" не найден.\n"; } } // Редактирование товара void editProduct(vector<Product>& products) { if (products.empty()) { cout << "\nСписок товаров пуст.\n"; return; } showProducts(products); int index = inputInt("\nВведите номер товара для редактирования: ") - 1; if (index >= 0 && index < (int)products.size()) { cout << "\n===== РЕДАКТИРОВАНИЕ ТОВАРА =====\n"; cout << "Текущая информация:\n"; cout << " Название: " << products[index].name << endl; cout << " Количество: " << products[index].quantity << endl; cout << " Цена: " << products[index].price << " руб.\n"; cout << "\nВведите новые данные (Enter - оставить без изменений):\n"; string newName; cout << "Новое название: "; getline(cin, newName); if (!newName.empty()) { products[index].name = newName; } string newQuantityStr; cout << "Новое количество: "; getline(cin, newQuantityStr); if (!newQuantityStr.empty()) { int newQuantity = stoi(newQuantityStr); if (newQuantity >= 0) { products[index].quantity = newQuantity; } } string newPriceStr; cout << "Новая цена: "; getline(cin, newPriceStr); if (!newPriceStr.empty()) { double newPrice = stod(newPriceStr); if (newPrice >= 0) { products[index].price = newPrice; } } // Пересчет стоимости products[index].totalPrice = products[index].quantity * products[index].price; cout << "\nТовар успешно обновлен!\n"; } else { cout << "Неверный номер товара.\n"; } } // Удаление товара void deleteProduct(vector<Product>& products) { if (products.empty()) { cout << "\nСписок товаров пуст.\n"; return; } showProducts(products); int index = inputInt("\nВведите номер товара для удаления: ") - 1; if (index >= 0 && index < (int)products.size()) { cout << "\nТовар \"" << products[index].name << "\" успешно удален.\n"; products.erase(products.begin() + index); } else { cout << "Неверный номер товара.\n"; } } // Сохранение в файл void saveToFile(const vector<Product>& products) { ofstream file("warehouse.txt"); if (!file.is_open()) { cout << "Ошибка открытия файла для записи.\n"; return; } double warehouseTotal = 0; file << "===== СПИСОК ТОВАРОВ =====\n"; file << "------------------------------------------------\n"; for (size_t i = 0; i < products.size(); i++) { file << "\nТовар #" << i + 1 << "\n"; file << "Название: " << products[i].name << "\n"; file << "Количество: " << products[i].quantity << "\n"; file << "Цена: " << products[i].price << "\n"; file << "Стоимость: " << products[i].totalPrice << "\n"; warehouseTotal += products[i].totalPrice; } file << "\n------------------------------------------------\n"; file << "Общая стоимость склада: " << warehouseTotal << "\n"; file.close(); cout << "\nДанные успешно сохранены в файл warehouse.txt\n"; cout << "Сохранено товаров: " << products.size() << "\n"; } // Загрузка из файла void loadFromFile(vector<Product>& products) { ifstream file("warehouse.txt"); if (!file.is_open()) { cout << "Файл warehouse.txt не найден или не может быть открыт.\n"; return; } products.clear(); string line; Product p; bool readingProduct = false; while (getline(file, line)) { if (line.find("Название:") != string::npos) { size_t pos = line.find(":"); if (pos != string::npos) { p.name = line.substr(pos + 2); readingProduct = true; } } else if (line.find("Количество:") != string::npos && readingProduct) { size_t pos = line.find(":"); if (pos != string::npos) { p.quantity = stoi(line.substr(pos + 2)); } } else if (line.find("Цена:") != string::npos && readingProduct) { size_t pos = line.find(":"); if (pos != string::npos) { p.price = stod(line.substr(pos + 2)); } } else if (line.find("Стоимость:") != string::npos && readingProduct) { size_t pos = line.find(":"); if (pos != string::npos) { p.totalPrice = stod(line.substr(pos + 2)); products.push_back(p); readingProduct = false; } } } file.close(); if (!products.empty()) { cout << "\nДанные успешно загружены из файла warehouse.txt\n"; cout << "Загружено товаров: " << products.size() << "\n"; } else { cout << "\nФайл пуст или имеет неверный формат.\n"; } } // Очистка всех товаров void clearAllProducts(vector<Product>& products) { if (products.empty()) { cout << "\nСписок товаров уже пуст.\n"; return; } cout << "\n========================================\n"; cout << "ВНИМАНИЕ! Это действие удалит ВСЕ товары!\n"; cout << "========================================\n"; int confirm = inputInt("Для подтверждения введите 1: "); if (confirm == 1) { products.clear(); cout << "Все товары успешно удалены.\n"; } else { cout << "Операция отменена.\n"; } } // Главное меню void menu() { vector<Product> products; int choice; do { cout << "\n========================================\n"; cout << " СИСТЕМА УПРАВЛЕНИЯ СКЛАДОМ \n"; cout << "========================================\n"; cout << "1. Добавить товар(ы)\n"; cout << "2. Показать все товары\n"; cout << "3. Поиск товара\n"; cout << "4. Редактировать товар\n"; cout << "5. Удалить товар\n"; cout << "6. Сохранить в файл\n"; cout << "7. Загрузить из файла\n"; cout << "8. Очистить весь склад\n"; cout << "9. Выход\n"; cout << "========================================\n"; choice = inputInt("Выберите пункт меню (1-9): "); switch (choice) { case 1: addProducts(products); break; case 2: showProducts(products); break; case 3: searchProduct(products); break; case 4: editProduct(products); break; case 5: deleteProduct(products); break; case 6: saveToFile(products); break; case 7: loadFromFile(products); break; case 8: clearAllProducts(products); break; case 9: cout << "\nПрограмма завершена. Спасибо за использование!\n"; break; default: cout << "Неверный пункт меню. Пожалуйста, выберите 1-9.\n"; } } while (choice != 9); } int main() { // Устанавливаем русскую кодировку setRussianConsole(); cout << "========================================\n"; cout << " ДОБРО ПОЖАЛОВАТЬ В СИСТЕМУ СКЛАДА \n"; cout << "========================================\n"; menu(); return 0; }