Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define NOMINMAX
- #include <windows.h>
- #include <iostream>
- #include <string>
- #include <limits>
- #include <fstream>
- #include <sstream>
- using namespace std;
- template<typename T>
- struct Node {
- T data;
- Node* next;
- Node(T val) : data(val), next(nullptr) {}
- };
- template<typename T>
- class LinkedList {
- private:
- Node<T>* head;
- public:
- LinkedList() : head(nullptr) {}
- void push_back(T value) {
- Node<T>* newNode = new Node<T>(value);
- if (head == nullptr) {
- head = newNode;
- }
- else {
- Node<T>* temp = head;
- while (temp->next != nullptr) {
- temp = temp->next;
- }
- temp->next = newNode;
- }
- }
- void remove_at(int position) {
- Node<T>* temp = head;
- if (position == 0) {
- head = head->next;
- delete temp;
- return;
- }
- for (int i = 0; temp != nullptr and i < position - 1; ++i) {
- temp = temp->next;
- }
- Node<T>* nodeToDelete = temp->next;
- temp->next = temp->next->next;
- delete nodeToDelete;
- }
- void print() const {
- Node<T>* temp = head;
- while (temp != nullptr) {
- temp->data.print();
- cout << '\n';
- temp = temp->next;
- }
- }
- int size() const {
- int count = 0;
- Node<T>* temp = head;
- while (temp != nullptr) {
- count++;
- temp = temp->next;
- }
- return count;
- }
- T& get(int index) {
- Node<T>* temp = head;
- for (int i = 0; temp != nullptr and i < index; ++i) {
- temp = temp->next;
- }
- return temp->data;
- }
- ~LinkedList() {
- Node<T>* current = head;
- Node<T>* nextNode;
- while (current != nullptr) {
- nextNode = current->next;
- delete current;
- current = nextNode;
- }
- }
- void save_to_file(const string& filename) {
- ofstream file(filename, ios::binary);
- if (!file) {
- cerr << "Ошибка открытия файла для записи!\n";
- return;
- }
- Node<T>* temp = head;
- while (temp != nullptr) {
- temp->data.serialize(file);
- temp = temp->next;
- }
- file.close();
- }
- void load_from_file(const string& filename) {
- ifstream file(filename, ios::binary);
- if (!file) {
- cerr << "Ошибка открытия файла для чтения!\n";
- return;
- }
- T data;
- while (data.deserialize(file)) {
- push_back(data);
- }
- file.close();
- }
- void save_to_text_file(const string& filename) const {
- ofstream file(filename);
- if (!file) {
- cerr << "Ошибка открытия файла для записи!\n";
- return;
- }
- Node<T>* temp = head;
- while (temp != nullptr) {
- file << temp->data.to_text();
- temp = temp->next;
- }
- file.close();
- }
- };
- class Product {
- public:
- Product() : name(""), weight(0), price(0), life(0) {}
- Product(string namee, int weightt, int pricee, int lifee) {
- this->name = namee;
- this->weight = weightt;
- this->price = pricee;
- this->life = lifee;
- }
- void print() const {
- cout << "Название продукта: " << this->name << '\n'
- << "Вес продукта: " << this->weight << '\n'
- << "Цена продукта: " << this->price << '\n'
- << "Срок годности продукта: " << this->life << '\n';
- if (life <= 2) {
- cout << "Данный товар идёт по уценке!\n";
- }
- }
- string get_name() const {
- return this->name;
- }
- void serialize(ofstream& file) const {
- size_t nameSize = name.size();
- file.write(reinterpret_cast<const char*>(&nameSize), sizeof(nameSize));
- file.write(name.c_str(), nameSize);
- file.write(reinterpret_cast<const char*>(&weight), sizeof(weight));
- file.write(reinterpret_cast<const char*>(&price), sizeof(price));
- file.write(reinterpret_cast<const char*>(&life), sizeof(life));
- }
- bool deserialize(ifstream& file) {
- size_t nameSize;
- file.read(reinterpret_cast<char*>(&nameSize), sizeof(nameSize));
- if (file.eof()) return false;
- name.resize(nameSize);
- file.read(&name[0], nameSize);
- file.read(reinterpret_cast<char*>(&weight), sizeof(weight));
- file.read(reinterpret_cast<char*>(&price), sizeof(price));
- file.read(reinterpret_cast<char*>(&life), sizeof(life));
- return true;
- }
- string to_text() const {
- stringstream ss;
- ss << "------------------\n";
- ss << "Имя товара: " << name << "\n";
- ss << "Вес товара: " << weight << "\n";
- ss << "Цена товара: " << price << "\n";
- ss << "Срок годности товара: " << life << "\n";
- if (life <= 2) {
- ss << "Данный товар идёт по уценке!\n";
- }
- ss << "------------------";
- return ss.str();
- }
- private:
- string name;
- int weight;
- int price;
- int life;
- template<typename T>
- friend class LinkedList;
- };
- void add_product(LinkedList<Product>& database) {
- cout << "\tДобавление продукта в список\n";
- cin.ignore(numeric_limits<streamsize>::max(), '\n');
- cout << "Введите название продукта: ";
- string name;
- getline(cin, name);
- cout << '\n';
- cout << "Введите вес продукта: ";
- int weight;
- while (true) {
- cin >> weight;
- if (cin.fail() or weight <= 0) {
- cin.clear();
- cin.ignore(numeric_limits<streamsize>::max(), '\n');
- cout << "Некорректный ввод. Пожалуйста, введите положительное число: ";
- }
- else {
- cin.ignore(numeric_limits<streamsize>::max(), '\n');
- break;
- }
- }
- cout << '\n';
- cout << "Введите цену продукта: ";
- int price;
- while (true) {
- cin >> price;
- if (cin.fail() or price <= 0) {
- cin.clear();
- cin.ignore(numeric_limits<streamsize>::max(), '\n');
- cout << "Некорректный ввод. Пожалуйста, введите положительное число: ";
- }
- else {
- break;
- }
- }
- cout << '\n';
- cout << "Введите срок годности продукта в днях: ";
- int life;
- while (true) {
- cin >> life;
- if (cin.fail() or life <= 0) {
- cin.clear();
- cin.ignore(numeric_limits<streamsize>::max(), '\n');
- cout << "Некорректный ввод. Пожалуйста, введите положительное число: ";
- }
- else {
- break;
- }
- }
- database.push_back(Product(name, weight, price, life));
- }
- void delete_product(LinkedList<Product>& database, int index) {
- database.remove_at(index - 1);
- }
- int main() {
- SetConsoleOutputCP(1251);
- SetConsoleCP(1251);
- setlocale(LC_ALL, "Russian");
- LinkedList<Product> DateBase;
- while (true) {
- cout << "\tМеню\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 << "Введите номер необходимого пункта: ";
- int choice;
- while (true) {
- cin >> choice;
- if (cin.fail() or choice <= 0) {
- cin.clear();
- cin.ignore(numeric_limits<streamsize>::max(), '\n');
- cout << "Некорректный ввод. Пожалуйста, введите положительное число: ";
- }
- else {
- break;
- }
- }
- switch (choice) {
- case 1: {
- system("cls");
- add_product(DateBase);
- system("pause");
- system("cls");
- break;
- }
- case 2: {
- system("cls");
- int dbSize = DateBase.size();
- if (dbSize == 0) {
- cout << "В вашем списке ничего нет!\n";
- system("pause");
- system("cls");
- break;
- }
- for (int i = 0; i < dbSize; ++i) {
- cout << i + 1 << ". " << DateBase.get(i).get_name() << '\n';
- }
- cout << "Введите индекс продукта, который нужно удалить: ";
- int index;
- while (true) {
- cin >> index;
- if (cin.fail() or index <= 0 or index > dbSize) {
- cin.clear();
- cin.ignore(numeric_limits<streamsize>::max(), '\n');
- cout << "Некорректный ввод. Пожалуйста, введите число из доступного диапазона: ";
- }
- else {
- break;
- }
- }
- delete_product(DateBase, index);
- system("pause");
- system("cls");
- break;
- }
- case 3: {
- system("cls");
- if (DateBase.size() == 0) {
- cout << "В вашем списке ничего нет!\n";
- system("pause");
- system("cls");
- break;
- }
- DateBase.print();
- system("pause");
- system("cls");
- break;
- }
- case 4: {
- system("cls");
- DateBase.save_to_file("products.bin");
- cout << "Список сохранен в бинарный файл.\n";
- system("pause");
- system("cls");
- break;
- }
- case 5: {
- system("cls");
- DateBase.load_from_file("products.bin");
- cout << "Список загружен из бинарного файла.\n";
- system("pause");
- system("cls");
- break;
- }
- case 6: {
- system("cls");
- DateBase.save_to_text_file("products.txt");
- cout << "Список сохранен в текстовый файл.\n";
- system("pause");
- system("cls");
- break;
- }
- case 7: {
- return 0;
- }
- default:
- system("cls");
- break;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement