Advertisement
SillyWolfy

Lab 12

May 16th, 2024
734
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 11.48 KB | None | 0 0
  1. #define NOMINMAX
  2. #include <windows.h>
  3. #include <iostream>
  4. #include <string>
  5. #include <limits>
  6. #include <fstream>
  7. #include <sstream>
  8. using namespace std;
  9.  
  10. template<typename T>
  11. struct Node {
  12.     T data;
  13.     Node* next;
  14.  
  15.     Node(T val) : data(val), next(nullptr) {}
  16. };
  17.  
  18. template<typename T>
  19. class LinkedList {
  20. private:
  21.     Node<T>* head;
  22.  
  23. public:
  24.     LinkedList() : head(nullptr) {}
  25.  
  26.     void push_back(T value) {
  27.         Node<T>* newNode = new Node<T>(value);
  28.         if (head == nullptr) {
  29.             head = newNode;
  30.         }
  31.         else {
  32.             Node<T>* temp = head;
  33.             while (temp->next != nullptr) {
  34.                 temp = temp->next;
  35.             }
  36.             temp->next = newNode;
  37.         }
  38.     }
  39.  
  40.     void remove_at(int position) {
  41.         Node<T>* temp = head;
  42.         if (position == 0) {
  43.             head = head->next;
  44.             delete temp;
  45.             return;
  46.         }
  47.         for (int i = 0; temp != nullptr and i < position - 1; ++i) {
  48.             temp = temp->next;
  49.         }
  50.         Node<T>* nodeToDelete = temp->next;
  51.         temp->next = temp->next->next;
  52.         delete nodeToDelete;
  53.     }
  54.  
  55.     void print() const {
  56.         Node<T>* temp = head;
  57.         while (temp != nullptr) {
  58.             temp->data.print();
  59.             cout << '\n';
  60.             temp = temp->next;
  61.         }
  62.     }
  63.  
  64.     int size() const {
  65.         int count = 0;
  66.         Node<T>* temp = head;
  67.         while (temp != nullptr) {
  68.             count++;
  69.             temp = temp->next;
  70.         }
  71.         return count;
  72.     }
  73.  
  74.     T& get(int index) {
  75.         Node<T>* temp = head;
  76.         for (int i = 0; temp != nullptr and i < index; ++i) {
  77.             temp = temp->next;
  78.         }
  79.         return temp->data;
  80.     }
  81.  
  82.     ~LinkedList() {
  83.         Node<T>* current = head;
  84.         Node<T>* nextNode;
  85.         while (current != nullptr) {
  86.             nextNode = current->next;
  87.             delete current;
  88.             current = nextNode;
  89.         }
  90.     }
  91.  
  92.     void save_to_file(const string& filename) {
  93.         ofstream file(filename, ios::binary);
  94.         if (!file) {
  95.             cerr << "Ошибка открытия файла для записи!\n";
  96.             return;
  97.         }
  98.         Node<T>* temp = head;
  99.         while (temp != nullptr) {
  100.             temp->data.serialize(file);
  101.             temp = temp->next;
  102.         }
  103.         file.close();
  104.     }
  105.  
  106.     void load_from_file(const string& filename) {
  107.         ifstream file(filename, ios::binary);
  108.         if (!file) {
  109.             cerr << "Ошибка открытия файла для чтения!\n";
  110.             return;
  111.         }
  112.         T data;
  113.         while (data.deserialize(file)) {
  114.             push_back(data);
  115.         }
  116.         file.close();
  117.     }
  118.  
  119.     void save_to_text_file(const string& filename) const {
  120.         ofstream file(filename);
  121.         if (!file) {
  122.             cerr << "Ошибка открытия файла для записи!\n";
  123.             return;
  124.         }
  125.         Node<T>* temp = head;
  126.         while (temp != nullptr) {
  127.             file << temp->data.to_text();
  128.             temp = temp->next;
  129.         }
  130.         file.close();
  131.     }
  132. };
  133.  
  134. class Product {
  135. public:
  136.     Product() : name(""), weight(0), price(0), life(0) {}
  137.  
  138.     Product(string namee, int weightt, int pricee, int lifee) {
  139.         this->name = namee;
  140.         this->weight = weightt;
  141.         this->price = pricee;
  142.         this->life = lifee;
  143.     }
  144.  
  145.     void print() const {
  146.         cout << "Название продукта: " << this->name << '\n'
  147.             << "Вес продукта: " << this->weight << '\n'
  148.             << "Цена продукта: " << this->price << '\n'
  149.             << "Срок годности продукта: " << this->life << '\n';
  150.         if (life <= 2) {
  151.             cout << "Данный товар идёт по уценке!\n";
  152.         }
  153.     }
  154.  
  155.     string get_name() const {
  156.         return this->name;
  157.     }
  158.  
  159.     void serialize(ofstream& file) const {
  160.         size_t nameSize = name.size();
  161.         file.write(reinterpret_cast<const char*>(&nameSize), sizeof(nameSize));
  162.         file.write(name.c_str(), nameSize);
  163.         file.write(reinterpret_cast<const char*>(&weight), sizeof(weight));
  164.         file.write(reinterpret_cast<const char*>(&price), sizeof(price));
  165.         file.write(reinterpret_cast<const char*>(&life), sizeof(life));
  166.     }
  167.  
  168.     bool deserialize(ifstream& file) {
  169.         size_t nameSize;
  170.         file.read(reinterpret_cast<char*>(&nameSize), sizeof(nameSize));
  171.         if (file.eof()) return false;
  172.         name.resize(nameSize);
  173.         file.read(&name[0], nameSize);
  174.         file.read(reinterpret_cast<char*>(&weight), sizeof(weight));
  175.         file.read(reinterpret_cast<char*>(&price), sizeof(price));
  176.         file.read(reinterpret_cast<char*>(&life), sizeof(life));
  177.         return true;
  178.     }
  179.  
  180.     string to_text() const {
  181.         stringstream ss;
  182.         ss << "------------------\n";
  183.         ss << "Имя товара: " << name << "\n";
  184.         ss << "Вес товара: " << weight << "\n";
  185.         ss << "Цена товара: " << price << "\n";
  186.         ss << "Срок годности товара: " << life << "\n";
  187.         if (life <= 2) {
  188.             ss << "Данный товар идёт по уценке!\n";
  189.         }
  190.         ss << "------------------";
  191.         return ss.str();
  192.     }
  193.  
  194. private:
  195.     string name;
  196.     int weight;
  197.     int price;
  198.     int life;
  199.  
  200.     template<typename T>
  201.     friend class LinkedList;
  202. };
  203.  
  204. void add_product(LinkedList<Product>& database) {
  205.     cout << "\tДобавление продукта в список\n";
  206.     cin.ignore(numeric_limits<streamsize>::max(), '\n');
  207.     cout << "Введите название продукта: ";
  208.     string name;
  209.     getline(cin, name);
  210.     cout << '\n';
  211.     cout << "Введите вес продукта: ";
  212.     int weight;
  213.     while (true) {
  214.         cin >> weight;
  215.         if (cin.fail() or weight <= 0) {
  216.             cin.clear();
  217.             cin.ignore(numeric_limits<streamsize>::max(), '\n');
  218.             cout << "Некорректный ввод. Пожалуйста, введите положительное число: ";
  219.         }
  220.         else {
  221.             cin.ignore(numeric_limits<streamsize>::max(), '\n');
  222.             break;
  223.         }
  224.     }
  225.     cout << '\n';
  226.     cout << "Введите цену продукта: ";
  227.     int price;
  228.     while (true) {
  229.         cin >> price;
  230.         if (cin.fail() or price <= 0) {
  231.             cin.clear();
  232.             cin.ignore(numeric_limits<streamsize>::max(), '\n');
  233.             cout << "Некорректный ввод. Пожалуйста, введите положительное число: ";
  234.         }
  235.         else {
  236.             break;
  237.         }
  238.     }
  239.     cout << '\n';
  240.     cout << "Введите срок годности продукта в днях: ";
  241.     int life;
  242.     while (true) {
  243.         cin >> life;
  244.         if (cin.fail() or life <= 0) {
  245.             cin.clear();
  246.             cin.ignore(numeric_limits<streamsize>::max(), '\n');
  247.             cout << "Некорректный ввод. Пожалуйста, введите положительное число: ";
  248.         }
  249.         else {
  250.             break;
  251.         }
  252.     }
  253.     database.push_back(Product(name, weight, price, life));
  254. }
  255.  
  256. void delete_product(LinkedList<Product>& database, int index) {
  257.     database.remove_at(index - 1);
  258. }
  259.  
  260. int main() {
  261.     SetConsoleOutputCP(1251);
  262.     SetConsoleCP(1251);
  263.     setlocale(LC_ALL, "Russian");
  264.  
  265.     LinkedList<Product> DateBase;
  266.  
  267.     while (true) {
  268.         cout << "\tМеню\n";
  269.         cout << "Необходимо выбрать один из пунктов:\n";
  270.         cout << "1) Добавить продукт в список\n";
  271.         cout << "2) Удалить продукт из списка\n";
  272.         cout << "3) Вывести список\n";
  273.         cout << "4) Сохранить список в бинарный файл\n";
  274.         cout << "5) Загрузить список из бинарного файла\n";
  275.         cout << "6) Сохранить список в текстовый файл\n";
  276.         cout << "7) Закончить программу\n";
  277.         cout << "Введите номер необходимого пункта: ";
  278.         int choice;
  279.         while (true) {
  280.             cin >> choice;
  281.             if (cin.fail() or choice <= 0) {
  282.                 cin.clear();
  283.                 cin.ignore(numeric_limits<streamsize>::max(), '\n');
  284.                 cout << "Некорректный ввод. Пожалуйста, введите положительное число: ";
  285.             }
  286.             else {
  287.                 break;
  288.             }
  289.         }
  290.         switch (choice) {
  291.         case 1: {
  292.             system("cls");
  293.             add_product(DateBase);
  294.             system("pause");
  295.             system("cls");
  296.             break;
  297.         }
  298.         case 2: {
  299.             system("cls");
  300.             int dbSize = DateBase.size();
  301.             if (dbSize == 0) {
  302.                 cout << "В вашем списке ничего нет!\n";
  303.                 system("pause");
  304.                 system("cls");
  305.                 break;
  306.             }
  307.             for (int i = 0; i < dbSize; ++i) {
  308.                 cout << i + 1 << ". " << DateBase.get(i).get_name() << '\n';
  309.             }
  310.             cout << "Введите индекс продукта, который нужно удалить: ";
  311.             int index;
  312.             while (true) {
  313.                 cin >> index;
  314.                 if (cin.fail() or index <= 0 or index > dbSize) {
  315.                     cin.clear();
  316.                     cin.ignore(numeric_limits<streamsize>::max(), '\n');
  317.                     cout << "Некорректный ввод. Пожалуйста, введите число из доступного диапазона: ";
  318.                 }
  319.                 else {
  320.                     break;
  321.                 }
  322.             }
  323.             delete_product(DateBase, index);
  324.             system("pause");
  325.             system("cls");
  326.             break;
  327.         }
  328.         case 3: {
  329.             system("cls");
  330.             if (DateBase.size() == 0) {
  331.                 cout << "В вашем списке ничего нет!\n";
  332.                 system("pause");
  333.                 system("cls");
  334.                 break;
  335.             }
  336.             DateBase.print();
  337.             system("pause");
  338.             system("cls");
  339.             break;
  340.         }
  341.         case 4: {
  342.             system("cls");
  343.             DateBase.save_to_file("products.bin");
  344.             cout << "Список сохранен в бинарный файл.\n";
  345.             system("pause");
  346.             system("cls");
  347.             break;
  348.         }
  349.         case 5: {
  350.             system("cls");
  351.             DateBase.load_from_file("products.bin");
  352.             cout << "Список загружен из бинарного файла.\n";
  353.             system("pause");
  354.             system("cls");
  355.             break;
  356.         }
  357.         case 6: {
  358.             system("cls");
  359.             DateBase.save_to_text_file("products.txt");
  360.             cout << "Список сохранен в текстовый файл.\n";
  361.             system("pause");
  362.             system("cls");
  363.             break;
  364.         }
  365.         case 7: {
  366.             return 0;
  367.         }
  368.         default:
  369.             system("cls");
  370.             break;
  371.         }
  372.     }
  373. }
  374.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement