Загрузка данных


cpp
#include <iostream>
#include <vector>
#include <string>
#include <iomanip> // Для красивого вывода таблицы

using namespace std;

// Структура данных (Сущность по ТЗ)
class Component {
public:
    int id;
    string name;
    string type;
    double price;
    int quantity;

    Component(int id, string name, string type, double price, int quantity) {
        this->id = id;
        this->name = name;
        this->type = type;
        this->price = price;
        this->quantity = quantity;
    }

    void display() const {
        cout << setw(5) << id << " | " 
             << setw(15) << name << " | " 
             << setw(10) << type << " | " 
             << setw(10) << fixed << setprecision(2) << price << " руб. | " 
             << setw(5) << quantity << " шт." << endl;
    }
};

// Логика управления складом
class Warehouse {
private:
    vector<Component> inventory;

public:
    void addComponent() {
        int id, qty;
        string name, type;
        double price;

        cout << "\n--- Добавление нового компонента ---\n";
        cout << "Введите ID: ";
        if (!(cin >> id)) { throw string("Ошибка: ID должен быть числом"); }
        
        cout << "Название: ";
        cin.ignore(); // Очистка буфера после ввода числа
        getline(cin, name);
        
        cout << "Тип (CPU/RAM/GPU): ";
        getline(cin, type);
        
        cout << "Цена: ";
        if (!(cin >> price) || price < 0) { throw string("Ошибка: некорректная цена"); }
        
        cout << "Количество: ";
        if (!(cin >> qty) || qty < 0) { throw string("Ошибка: некорректное количество"); }

        inventory.push_back(Component(id, name, type, price, qty));
        cout << "Запись успешно добавлена!\n";
    }

    void showAll() const {
        cout << "\n--- Текущий склад ---\n";
        if (inventory.empty()) {
            cout << "Склад пуст.\n";
            return;
        }
        for (const auto& item : inventory) {
            item.display();
        }
    }

    void findByType() const {
        string searchType;
        cout << "\nВведите категорию для поиска: ";
        cin >> searchType;
        
        bool found = false;
        for (const auto& item : inventory) {
            if (item.type == searchType) {
                item.display();
                found = true;
            }
        }
        if (!found) cout << "Компоненты категории " << searchType << " не найдены.\n";
    }

    void calculateTotal() const {
        double total = 0;
        for (const auto& item : inventory) {
            total += item.price * item.quantity;
        }
        cout << "\nОбщая стоимость всех активов: " << fixed << setprecision(2) << total << " руб.\n";
    }
};

int main() {
    setlocale(LC_ALL, "Russian"); // Корректное отображение кириллицы
    Warehouse myWarehouse;
    int choice;

    while (true) {
        cout << "\n1. Добавить компонент\n"
             << "2. Показать все\n"
             << "3. Поиск по типу\n"
             << "4. Расчет общей стоимости\n"
             << "0. Выход\n"
             << "Выберите пункт меню: ";
        
        if (!(cin >> choice)) {
            cout << "Критическая ошибка ввода!";
            break;
        }

        try {
            switch (choice) {
                case 1: myWarehouse.addComponent(); break;
                case 2: myWarehouse.showAll(); break;
                case 3: myWarehouse.findByType(); break;
                case 4: myWarehouse.calculateTotal(); break;
                case 0: return 0;
                default: cout << "Неверный пункт меню.\n";
            }
        } catch (const string& errorMsg) {
            cout << errorMsg << endl;
            cin.clear(); // Сброс состояния ошибки потока
            cin.ignore(10000, '\n'); // Очистка буфера
        }
    }
    return 0;
}