Скачиваний:
40
Добавлен:
05.07.2021
Размер:
676.99 Кб
Скачать

3 Индивидуальное задание

На основе разработанной иерархии классов, реализованной во второй лабораторной работе, реализовать программу работы с данными, используя потоки ввода-вывода. Реализовать функций добавления, удаления, редактирования и просмотра данных, поиска данных по необходимым параметрам.

4 Код решения индивидуального задания

#include "transaction.h"

#include <vector>

#include <fstream>

#include <Windows.h>

using namespace std;

namespace menu

{

template <class T>

T transactMenu(T*);

};

class Order; //класс который содержит инфу о скачиваниях

class Shop; //класс который предоставляет возможность приобрести лицензию на программу котору можно скачать

class Customer; //класс который содержит в себе инфу о пользователях

class Goods; //класс который содержит в себе инфу о всехвозможных пргаммах которые можно скачать

class MyException; //класс иключения

void spaceDestroyer(string&);

void pointDestroyer(string&);

void fread(vector<Customer>&);

void fwrite(vector<Customer>);

class MyException : public std::exception

{

private:

string error;

public:

MyException(string error)

{

this->error = error;

}

string what()

{

return this->error;

}

};

class Goods

{

private:

friend class Shop;

int* error;

public:

unsigned int count;

string name;

double price;

Goods(int count)

{

try

{

int count = 0;

while (true)

{

cout << count << endl;

count++;

error = new int[100000000];

}

}

catch (bad_alloc exeption) {

cout << "Ошибка выделения:" << exeption.what() << endl;

system("pause");

return;

}

}

Goods(const Goods& goods, int count)

{

this->name = goods.name;

this->price = goods.price;

this->count = count;

}

Goods()

{

cout << endl << "Объект \"Программа\" создан" << endl;

}

void output()

{

cout << " " << setw(23) << name;

cout << " || " << setw(8) << price;

cout << " || " << count << endl;

}

void input()

{

while (true)

{

cout << "Наименование программы : ";

cin >> name;

try {

cout << "Цена за скачивание лицензии: ";

cin >> price;

cout << "Кол-во преобретающих лицензий этой программы: ";

cin >> count;

break;

}

catch (exception error)

{

cin.clear();

cin.ignore(32767, '\n');

cout << error.what() << endl;

system("pause");

}

}

}

void set(Goods goods)

{

this->name = goods.name;

this->count = goods.count;

this->price = goods.price;

}

};

class Order

{

public:

friend class Customer;

int key;

vector<Goods> order;

double getTotalPrice()

{

double totalPrice = 0;

for (int i = 0; i < order.size(); i++)

{

totalPrice += (order.at(i).price * order.at(i).count);

}

return totalPrice;

}

int getTotalCount()

{

int totalCount = 0;

for (int i = 0; i < order.size(); i++)

{

totalCount += order.at(i).count;

}

return totalCount;

}

Order() { this->key = 0; }

~Order() { }

void output()

{

cout << " " << setw(25) << "Наименование программы";

cout << " Цена за лицензию ";

cout << " Кол-во" << endl;

double totalPrice = 0;

for (int i = 0; i < order.size(); i++)

{

order.at(i).output();

totalPrice += (order.at(i).price * order.at(i).price);

}

cout << "Стоимость : " << getTotalPrice() << endl;

}

void fread(ifstream& file)

{

file >> key;

cout << key;

while (true)

{

Goods goods;

file >> goods.name;

pointDestroyer(goods.name);

file >> goods.price;

file >> goods.count;

order.push_back(goods);

if (file.eof() || file.get() == '\n') return;

}

}

void fwrite(ofstream& file)

{

file << key;

for (int i = 0; i < order.size(); i++)

{

spaceDestroyer(order.at(i).name);

file << " " << order.at(i).name;

pointDestroyer(order.at(i).name);

file << " " << order.at(i).price;

file << " " << order.at(i).count;

}

}

};

class Customer

{

public:

string name;

double amountOfMoney;

vector<Order> orders;

static void headOfTable()

{

cout << " " << setiosflags(ios::left) << setw(25) << "Имя";

cout << "Баланс";

cout << " Кол-во скачиваний" << endl;

}

void fread(ifstream& file)

{

file >> name;

pointDestroyer(name);

file >> amountOfMoney;

int i = 0;

while (!file.eof())

{

Order newOrder;

newOrder.fread(file);

orders.push_back(newOrder);

}

}

Customer(const Customer& customer)

{

this->name = customer.name;

this->amountOfMoney = customer.amountOfMoney;

this->orders = customer.orders;

}

Customer()

{

cout << endl << "Объект \"Пользователь\" создан" << endl;

system("pause");

}

~Customer()

{

cout << endl << "Объект \"Пользователь\" удален" << endl;

system("pause");

}

void fwrite(int i)

{

string iFileName = "customer";

iFileName += (i + '0');

iFileName += ".txt";

ofstream file(iFileName);

spaceDestroyer(name);

file << endl << name;

pointDestroyer(name);

file << endl << amountOfMoney;

if (orders.size()) file << endl;

for (int i = 0; i < orders.size(); i++)

{

orders.at(i).fwrite(file);

if (orders.size() - i > 1) file << endl;

}

file.close();

}

void input()

{

cout << "Имя Пользователя : ";

cin >> name;

try {

cout << "Баланс : ";

cin >> amountOfMoney;

}

catch (exception error)

{

cin.clear();

cin.ignore(32767, '\n');

cout << error.what() << endl;

system("pause");

}

}

void output()

{

cout << " " << setw(23) << name;

cout << " || " << setw(17) << amountOfMoney;

cout << " || " << orders.size() << endl;

}

void set(Customer customer)

{

this->name = customer.name;

this->amountOfMoney = customer.amountOfMoney;

this->orders = customer.orders;

}

};

class Shop

{

bool fread()

{

bool status;

ifstream file("PO.txt");

if (file.get() != EOF)

{

file >> name;

pointDestroyer(name);

int i = 0;

while (!file.eof())

{

Goods goods;

file >> goods.count;

file >> goods.name;

pointDestroyer(goods.name);

file >> goods.price;

products.push_back(goods);

}

status = true;

}

else status = false;

file.close();

return status;

}

public:

string name;

vector<Goods> products;

void deleteFromOrder(Order& order)

{

order.output();

string goodsName;

cout << "Наименование ПО : ";

cin >> goodsName;

for (int i = 0; i < order.order.size(); i++)

{

if (goodsName == order.order.at(i).name)

{

for (int j = 0; j < products.size(); j++)

{

if (products.at(j).name == order.order.at(i).name)

{

products.at(i).count += order.order.at(i).count;

}

}

order.order.erase(i + order.order.begin());

cout << "ПО " << goodsName << " удален " << endl;

system("pause");

return;

}

}

cout << "Неверный ввод" << endl;

system("pause");

}

void addToOrder(Order& order)

{

system("cls");

if (!products.size())

{

cout << "Каталог пуст" << endl;

system("pause");

return;

}

cout << " " << setw(25) << "";

for (int i = 0; i < products.size(); i++)

{

products.at(i).output();

}

string name;

cout << "Наименование ПО : ";

cin >> name;

system("cls");

bool status = false;

for (int i = 0; i < products.size(); i++)

{

if (name == products.at(i).name && products.at(i).count)

{

products.at(i).output();

unsigned int count;

try {

cout << "Кол-во : ";

cin >> count;

}

catch (exception error)

{

cin.clear();

cin.ignore(32767, '\n');

cout << error.what() << endl;

system("pause");

}

status = true;

if (products.at(i).count >= count)

{

Goods goods(products.at(i), count);

products.at(i).count -= count;

bool orderStatus = false;

for (int j = 0; i < order.order.size(); i++)

{

if (order.order.at(i).name == goods.name)

{

order.order.at(i).count += goods.count;

orderStatus = true;

}

}

if (!orderStatus)

{

order.order.push_back(goods);

}

}

}

}

if (!status)

{

cout << "Данная лицензия на ПО отсутствует" << endl;

system("pause");

}

return;

}

void searchOrder(Order& order)

{

system("cls");

if (!products.size())

{

cout << "Каталог пуст" << endl;

system("pause");

return;

}

string name;

cout << "Наименование ПО : ";

cin >> name;

system("cls");

bool status = false;

for (int i = 0; i < products.size(); i++)

{

if (name == products.at(i).name && products.at(i).count)

{

products.at(i).output();

status = true;

system("pause");

}

}

if (!status)

{

cout << "Данная лицензия на ПО отсутствует" << endl;

system("pause");

}

return;

}

Shop()

{

cout << endl << "Объект \"сайт скачиваний\" создан" << endl;

if (!fread()) input();

else cout << "Данные считаны из файла" << endl;

system("pause");

}

~Shop()

{

cout << endl << "Объект \"сайт скачиваний\" удален" << endl;

fwrite();

system("pause");

}

void fwrite()

{

ofstream file("PO.txt");

spaceDestroyer(name);

file << endl << name;

pointDestroyer(name);

for (int i = 0; i < products.size(); i++)

{

file << endl << products.at(i).count;

spaceDestroyer(products.at(i).name);

file << endl << products.at(i).name;

pointDestroyer(products.at(i).name);

file << endl << products.at(i).price;

}

file.close();

}

void input()

{

cout << "Наименование сайта скачиваний : ";

cin >> name;

fwrite();

}

void inputGoods()

{

system("cls");

string name;

cout << "Наименование программы : ";

cin >> name;

for (int i = 0; i < products.size(); i++)

{

if (name == products.at(i).name)

{

cout << " " << setw(25) << "Наименование программы";

cout << " Цена ";

cout << " Кол-во" << endl;

products.at(i).output();

try {

cout << "Добавить лицензию : ";

unsigned int count;

cin >> count;

products.at(i).count += count;

return;

}

catch (exception error)

{

cin.clear();

cin.ignore(32767, '\n');

cout << error.what() << endl;

system("pause");

}

}

}

Goods goods;

goods.name = name;

try

{

cout << "Цена : ";

cin >> goods.price;

cout << "Кол-во : ";

cin >> goods.count;

products.push_back(goods);

}

catch (exception error)

{

cin.clear();

cin.ignore(32767, '\n');

cout << error.what() << endl;

system("pause");

}

}

void deleteGoods()

{

system("cls");

if (!products.size())

{

cout << "Каталог пуст" << endl;

system("pause");

return;

}

cout << " " << setw(25) << "Наименование ПО";

cout << " Цена ";

cout << " Кол-во доступных лицензий" << endl;

for (int i = 0; i < products.size(); i++)

{

products.at(i).output();

}

string name;

cout << "Наименование ПО : ";

cin >> name;

bool status = false;

for (int i = 0; i < products.size(); i++)

{

if (name == products.at(i).name)

{

products.erase(i + products.begin());

status = true;

}

}

if (!status)

{

cout << "Данный ПО отсутствует" << endl;

system("pause");

return;

}

}

void changeGoods()

{

system("cls");

if (!products.size())

{

cout << "Каталог пуст" << endl;

system("pause");

return;

}

cout << " " << setw(25) << "Наименование ПО";

cout << " Цена ";

cout << " Кол-во доступных лицензий" << endl;

for (int i = 0; i < products.size(); i++)

{

products.at(i).output();

}

string name;

cout << "Наименование ПО : ";

cin >> name;

bool status = false;

for (int i = 0; i < products.size(); i++)

{

if (name == products.at(i).name)

{

products.at(i) = menu::transactMenu<Goods>(&products.at(i));

status = true;

}

}

if (!status)

{

cout << "эта лицензия отсутствует" << endl;

system("pause");

return;

}

}

};

void spaceDestroyer(string& str)

{

for (int i = 0; i < str.size(); i++)

{

if (str.at(i) == ' ') str.at(i) = '.';

}

}

void pointDestroyer(string& str)

{

for (int i = 0; i < str.size(); i++)

{

if (str.at(i) == '.') str.at(i) = ' ';

}

}

void fread(vector<Customer>& customers)

{

const string fileName = "customer";

int i = 0;

while (true)

{

string iFileName = fileName;

string str;

iFileName += (i + '0');

iFileName += ".txt";

ifstream file;

i++;

try {

file.open(iFileName);

if (!file.is_open())

{

string errorText = "Ошибка чтения\nФайл ";

errorText += iFileName;

errorText += " не доступен";

throw MyException(errorText);

}

Customer newCustomer;

newCustomer.fread(file);

customers.push_back(newCustomer);

file.close();

}

catch (MyException& exception) {

cout << exception.what() << endl;

system("pause");

break;

}

}

}

void fwrite(vector<Customer> customers)

{

for (int i = 0; i < customers.size(); i++)

{

customers.at(i).fwrite(i);

}

}

void badAllocExit()

{

cout << "Собственная функция завершения" << endl;

exit(1);

}

namespace menu

{

template <class T>

T transactMenu(T* object)

{

try {

Transaction<T> transaction(object);

T* newObject = new T;

while (true)

{

system("cls");

cout << "1. Начать транзакцию" << endl;

cout << "2. Откатить состаяние" << endl;

cout << "3. Просмотреть состояние транзакции" << endl;

cout << "4. Подтвердить транзакцию // Выйти" << endl;

cout << ">> ";

try {

int choice;

cin >> choice;

switch (choice)

{

case 1:

{

newObject->input();

transaction.BeginTransactions(newObject);

break;

}

case 2:

{

transaction.DeleteTransactions();

break;

}

case 3:

{

system("cls");

transaction.show();

system("pause");

break;

}

case 4:

{

object = transaction.currentState;

transaction.commit();

system("cls");

transaction.show();

transaction = NULL;

object->output();

system("pause");

return *object;

}

default: cout << "Неверный ввод" << endl; system("pause"); break;

}

}

catch (exception error)

{

cin.clear();

cin.ignore(32767, '\n');

cout << error.what() << endl;

system("pause");

}

}

}

catch (const std::bad_alloc& error) {

std::cout << "Ошибка выделения :" << error.what() << endl;

system("pause");

}

}

void orderMenu(Customer& me, Shop& shop)

{

Shop rollbackShop = shop;

Customer rollbackCustomer = me;

Order order;

while (true)

{

system("cls");

cout << "1. Добавить ПО к приобретению лицензии" << endl;

cout << "2. Удалить ПО из покупок" << endl;

cout << "3. Просмотреть текущие лицензии" << endl;

cout << "4. Оплатить лицензии к ПО // Выйти" << endl;

cout << "5. Отменить приобретение лицензии // Выйти" << endl;

cout << ">> ";

try {

int choice;

cin >> choice;

switch (choice)

{

case 1:

{

shop.addToOrder(order);

break;

}

case 2:

{

shop.deleteFromOrder(order);

break;

}

case 3:

{

if (!order.order.size()) cout << " пусто" << endl;

else order.output();

system("pause");

break;

}

case 4:

{

if (order.order.size() && me.amountOfMoney >= order.getTotalCount())

{

me.amountOfMoney -= order.getTotalCount();

me.orders.push_back(order);

return;

}

else

{

cout << "Недостаточно средств" << endl;

system("pause");

break;

}

}

case 5:

{

me = rollbackCustomer;

shop = rollbackShop;

return;

}

default: { cout << "Неверный ввод" << endl; system("pause"); break; }

}

}

catch (exception error)

{

cin.clear();

cin.ignore(32767, '\n');

cout << error.what() << endl;

system("pause");

}

}

}

void shopMenu(Customer me, int iteration)

{

Shop shop;

Order order;

while (true)

{

system("cls");

cout << " " << shop.name << endl;

cout << " меню пользователя" << endl;

cout << "1. купить лицензии " << endl;

cout << "2. Просмотр истории покупок лицензии" << endl;

cout << "3. Изменить свои данные" << endl;

cout<<"4. Поиск программ"<<endl;

cout << "5. вернуться" << endl;

cout << ">> ";

try {

int choice;

cin >> choice;

switch (choice)

{

case 1:

{

orderMenu(me, shop);

shop.fwrite();

me.fwrite(iteration);

break;

}

case 2:

{

system("cls");

if (!me.orders.size())

{

cout << "История приобреиений пуста" << endl;

system("pause");

break;

}

cout << " Ключ Кол-во лицензий Сумма " << endl;

for (int i = 0; i < me.orders.size(); i++)

{

cout << " " << setw(5) << me.orders.at(i).key;

cout << " || " << setw(17) << me.orders.at(i).getTotalCount();

cout << " || " << me.orders.at(i).getTotalPrice() << endl;

}

system("pause");

}

case 3:

{

me = transactMenu<Customer>(&me);

system("pause");

me.fwrite(iteration);

break;

}

case 4:

{

shop.searchOrder(order);

break;

}

case 5: return;

default: { cout << "Неверный ввод" << endl; system("pause"); break; }

}

}

catch (exception error)

{

cin.clear();

cin.ignore(32767, '\n');

cout << error.what() << endl;

system("pause");

}

}

}

void adminShopMenu(Customer& me, int iteration)

{

Shop shop;

Order order;

while (true)

{

system("cls");

cout << " " << shop.name << endl;

cout << "РЕЖИМ АДМИНИСТРАТОРА" << endl;

cout << "1)Скачать ПО на компьютер" << endl;

cout << "2)Просмотр истории скачивания" << endl;

cout << "3)Изменить свои данные" << endl;

cout << "4)Добавить программу для скачивания" << endl;

cout << "5)Удалить программу для скачивания (ADMIN ROOTS)" << endl;

cout << "6)Изменить права для скачивания" << endl;

cout << "7)Поиск программ" << endl;

cout << "8)Вернуться назад" << endl;

cout << ">> ";

try {

int choice;

cin >> choice;

switch (choice)

{

case 1:

{

orderMenu(me, shop);

shop.fwrite();

me.fwrite(iteration);

break;

}

case 2:

{

system("cls");

if (!me.orders.size())

{

cout << "История скачиваний ПО пуста" << endl;

system("pause");

break;

}

cout << " Ключ Кол-во лицензий Сумма " << endl;

for (int i = 0; i < me.orders.size(); i++)

{

cout << " " << setw(5) << me.orders.at(i).key;

cout << " || " << setw(17) << me.orders.at(i).getTotalCount();

cout << " || " << me.orders.at(i).getTotalPrice() << endl;

}

system("pause");

break;

}

case 3:

{

me = transactMenu<Customer>(&me);

system("pause");

me.fwrite(iteration);

break;

}

case 4:

{

shop.inputGoods();

shop.fwrite();

break;

}

case 5:

{

shop.deleteGoods();

shop.fwrite();

break;

}

case 6:

{

shop.changeGoods();

shop.fwrite();

}

case 7:

{

shop.searchOrder(order);

break;

}

case 8: return;

default: { cout << "Неверный ввод" << endl; system("pause"); break; }

}

}

catch (exception error)

{

cin.clear();

cin.ignore(32767, '\n');

cout << error.what() << endl;

system("pause");

}

}

}

void authMenu()

{

const string adminName = "Маргарита";

vector<Customer> customers;

fread(customers);

while (true)

{

system("cls");

cout << "1)Войти в свой аккаунт" << endl;

cout << "2)Зарегистрироваться" << endl;

cout << "3)Просмотр всех пользователей в системе скачивания ПО" << endl;

cout << "4)Выход bad_alloc и конструктор" << endl; //указывает что ресурс не может быть выделен из-за нехватки доступной памяти

cout << "5)Выход set_terminate" << endl;//Если программа не может найти подходящий обработчик для сгенерированной исключительной ситуации, то будет вызвана процедура завершения terminate() (ее также называют обработчиком завершения).

cout << "6)Выход" << endl;

cout <<"7)Опишите предназначение функции terminate() ?"<<endl;

cout << ">> ";

try {

int choice;

cin >> choice;

switch (choice)

{

case 7:

{

cout << "Если программа не может найти подходящий обработчик для сгенерированной исключительной ситуации, то будет вызвана процедура завершения terminate() (ее также называют обработчиком завершения)." << endl;

system("pause");

break;

}

case 1:

{

system("cls");

if (!customers.size())

{

cout << "Нет зарегестрированных пользователей" << endl;

system("pause");

break;

}

cout << " ВХОД" << endl;

string authName;

cout << "Ваше имя: ";

cin >> authName;

bool status = false;

for (int i = 0; i < customers.size(); i++)

{

if (customers.at(i).name == authName)

{

if (authName == adminName) adminShopMenu(customers.at(i), i);

else shopMenu(customers.at(i), i);

status = true;

}

}

if (!status)

{

cout << "Неверно введено имя" << endl;

system("pause");

}

break;

}

case 2:

{

system("cls");

cout << "Регистрация нового пользователя" << endl;

Customer newCustomer;

newCustomer.input();

newCustomer.fwrite(customers.size());

customers.push_back(newCustomer);

break;

}

case 3:

{

system("cls");

if (customers.empty())

{

cout << "Нет зарегестрированных пользователей" << endl;

system("pause");

break;

}

Customer::headOfTable();

for (int i = 0; i < customers.size(); i++)

{

customers.at(i).output();

}

system("pause");

break;

}

case 4:

{

fwrite(customers);

Goods goods(0);

return;

}

case 5:

{

fwrite(customers);

set_terminate(badAllocExit);

try

{

throw "Этот текст не будет в консоли";

}

catch (int)

{

cout << "И этот текст не будет в консоли";

}

}

case 6: fwrite(customers); return;

default: { cout << "Неверный ввод" << endl; system("pause"); break; }

}

}

catch (exception error)

{

cin.clear();

cin.ignore(32767, '\n');

cout << error.what() << endl;

system("pause");

}

}

}

};

int main()

{

SetConsoleCP(1251);

SetConsoleOutputCP(1251);

cin.exceptions(ios_base::failbit);

menu::authMenu();

}

Соседние файлы в папке лабы Салапура 2ая часть (4 семестр)