Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdlib.h"
- #include <conio.h>
- #include <cstring>
- #include <ctime>
- #include <iomanip>
- #include <iostream>
- #include <fstream>
- #include <string>
- #define nl printf("\n")
- // Сравнение дат
- bool timeCompare(std::tm Bought, int ShelfLife, std::tm Sold)
- {
- Bought.tm_hour += ShelfLife;
- time_t t1 = mktime(&Bought);
- time_t t2 = mktime(&Sold);
- if (t1 == -1 || t2 == -1) return false;
- if (t1 >= t2)
- {
- // Если первая дата больше или равна второй - возвращаем true
- return true;
- }
- else return false;
- }
- // Односвязный список
- typedef struct Buy {
- char vendorCode[9]; //Артикул
- int bought; //Купили
- std::tm Date = {}; //Дата покупки дд:мм:гг
- struct Buy *next; //Ссылка на следующий элемент списка
- } Buy;
- // Добавление элемента в конец
- void push(Buy **head, char VendorCode[9], int Bought, std::tm Date) {
- Buy *tmp = *head; //Создаём временный элемент для прохождения по head
- Buy *next = (Buy*)malloc(sizeof(Buy)); //Создаём контейнер для "следующего" элемента
- memcpy(next->vendorCode, VendorCode, 9); //Заполняем next
- next->bought = Bought; //Заполняем next
- next->Date = Date;
- next->next = nullptr;
- if (*head == nullptr) //Если элемент первый, то
- {
- (*head) = next; //Первый элемент равен next
- }
- else { //Иначе
- while (tmp->next != nullptr) //Проходим по tmp, пока уществует следующий элемент
- {
- tmp = tmp->next;
- }
- tmp->next = next; //Когда следующий элемент равен NULL (т.е. сейчас мы на последнем элементе в tmp) меняем значение следующего на next
- }
- }
- // Удаление элемента с VendorCode
- int pop(Buy **head, char VendorCode[9])
- {
- if (!head) return -1;
- Buy *prev = nullptr;
- Buy *current = (*head);
- while (current)
- {
- if (strcmp(current->vendorCode, VendorCode) == 0) {
- if (current == (*head)) {
- (*head) = current->next;
- }
- else {
- prev->next = current->next;
- }
- break;
- }
- if (!(current->next)) return -1;
- prev = current;
- current = current->next;
- }
- return 1;
- }
- // Чтение из файла
- int fscan(const char *name, Buy **head)
- {
- char line[256];
- std::ifstream ifs(name);
- if (!ifs) return -1;
- while (ifs.getline(line, 256)) {
- char VendorCode[9];
- int Bought;
- std::tm Date = {};
- sscanf(line, "%8s %d %d/%d/%d", VendorCode, &Bought, &Date.tm_mday, &Date.tm_mon, &Date.tm_year);
- Date.tm_mon--;
- Date.tm_year -= 1900;
- push(&(*head), VendorCode, Bought, Date);
- }
- ifs.close();
- return 1;
- }
- // Запись в файл
- void fprint(const char *name, Buy *head)
- {
- std::ofstream ofs(name);
- Buy *last = head;
- do //Пока существует список
- {
- ofs << last->vendorCode << " " << last->bought << " " << std::put_time(&last->Date, "%d/%m/%Y") << std::endl;
- last = last->next; //Перевод указателя
- nl;
- } while (last != head);
- ofs.close();
- }
- // Чтение с консоли
- void scan(Buy **head)
- {
- char VendorCode[9]{};
- int InStock;
- std::tm Date = {};
- std::cout << "Введите артикул: ";
- std::cin >> VendorCode;
- nl;
- std::cout << "Введите сколько поступило на склад: ";
- std::cin >> InStock;
- nl;
- std::cout << "Введите дату поступлления на склад: ";
- std::cin >> std::get_time(&Date, "%d/%m/%Y");
- nl;
- nl;
- push(&(*head), VendorCode, InStock, Date);
- }
- // Вывод на консоль
- void print(Buy *head)
- {
- if (!head) return; //Если не существует списка - выходим
- Buy *last = head;
- do //Пока существует список
- {
- printf("%s ", last->vendorCode); //Вывод
- printf("%d ", last->bought); //Вывод
- std::cout << std::put_time(&last->Date, "%d/%m/%Y");
- last = last->next; //Перевод указателя
- nl;
- } while (last != nullptr);
- }
- // Удаление слишком новых записей
- void toDate(Buy **head, std::tm time)
- {
- Buy *current = (*head);
- int cout = 0;
- do
- {
- current = current->next;
- cout++;
- } while (current != nullptr);
- current = *head;
- do
- {
- if (!timeCompare(time, 0, current->Date))
- {
- pop(head, current->vendorCode);
- }
- else
- {
- current = current->next;
- }
- cout--;
- } while (cout != 0);
- }
- // Кольцевой список
- typedef struct Stock
- {
- char vendorCode[9]; //Артикул
- int inStock; //Осталось на складе
- std::tm Date = {}; //Дата поступления дд:мм:гг
- int shelfLife; //Срок годности
- struct Stock *next; //Ссылка на следующий элемент списка
- } Stock;
- // Добавление элемента в конец
- void push(Stock **head, const char VendorCode[9], int InStock, std::tm Date, int ShelfLife) {
- Stock *tmp = *head; //Создаём временный элемент для прохождения по head
- Stock *next = (Stock*)malloc(sizeof(Stock)); //Создаём контейнер для "следующего" элемента
- memcpy(next->vendorCode, VendorCode, 9); //Заполняем next
- next->inStock = InStock; //Заполняем next
- next->Date = Date;
- next->shelfLife = ShelfLife; //Заполняем next
- if (*head == nullptr) //Если элемент первый, то
- {
- (*head) = next; //Первый элемент равен next
- }
- else { //Иначе
- while (tmp->next != (*head)) //Проходим по tmp, пока уществует следующий элемент
- {
- tmp = tmp->next;
- }
- tmp->next = next; //Когда следующий элемент равен NULL (т.е. сейчас мы на последнем элементе в tmp) меняем значение следующего на next
- }
- next->next = (*head); //Т.к. элемент вставляется в конце, то следующий элемент за последним равен NULL
- }
- // Удаление элемента с VendorCode
- int pop(Stock **head, char VendorCode[9])
- {
- Stock *current, *prev;
- prev = nullptr;
- current = (*head);
- do
- {
- prev = current;
- current = current->next;
- } while (current != (*head));
- while (current)
- {
- if (strcmp(current->vendorCode, VendorCode) == 0) {
- prev->next = current->next;
- if (current == *head)
- {
- *head = prev->next;
- }
- break;
- }
- prev = current;
- current = current->next;
- }
- return 1;
- }
- // Проверяет, хватит ли товара
- int isEnought(Stock **s_head, Buy *b_head)
- {
- Stock *current;
- current = *s_head;
- int cout = 0;
- do
- {
- current = current->next;
- cout++;
- } while (current != *s_head);
- int inStock = 0;
- do
- {
- if (strcmp((*s_head)->vendorCode, b_head->vendorCode) == 0 && timeCompare(b_head->Date, 0, (*s_head)->Date) && timeCompare((*s_head)->Date, (*s_head)->shelfLife, b_head->Date))
- {
- inStock += (*s_head)->inStock;
- (*s_head) = (*s_head)->next;
- }
- else
- {
- if (!strcmp((*s_head)->vendorCode, b_head->vendorCode) == 0)
- {
- (*s_head) = (*s_head)->next;
- }
- else
- {
- if (strcmp((*s_head)->vendorCode, b_head->vendorCode) == 0 && (!timeCompare(b_head->Date, 0, (*s_head)->Date) || !timeCompare((*s_head)->Date, (*s_head)->shelfLife, b_head->Date)))
- {
- pop(&(*s_head), b_head->vendorCode);
- }
- }
- }
- cout--;
- } while (cout != 0); //Проходим по списку и считаем количество всех элементов с VendorCode
- return inStock >= b_head->bought ? 1 : -1;
- }
- // Покупка со склада
- int buy(Stock **head, char VendorCode[9], int bought)
- {
- if (!head) return -1; //Если не существует списка - выходим
- Stock *current = (*head); //Ячейка "текущего" элемента
- do //Пока существует текущий элемент
- {
- if (strcmp(current->vendorCode, VendorCode) == 0) { //Сравниваем строки
- int delta = current->inStock - bought;
- int result = 1;
- if (delta > 0)
- {
- current->inStock -= bought;
- return 0;
- }
- if (delta == 0)
- {
- result = pop(head, VendorCode);
- return result == 1 ? 0 : -1;
- }
- if (delta < 0)
- {
- result = buy(&(current->next), VendorCode, -delta);
- if (result == -1) return -1;
- if (result == 0) result = pop(head, VendorCode);
- if (result == -1) return -1;
- }
- }
- current = current->next; //Обновляем текущий элемент
- } while (current != (*head));
- return 1;
- }
- // Чтение из файла
- int fscan(const char *name, Stock **head)
- {
- char line[256]{};
- std::ifstream ifs(name);
- if (!ifs) return -1;
- while (ifs.getline(line, 256)) {
- char VendorCode[9];
- int InStock;
- std::tm Date = {};
- int ShelfLife;
- sscanf(line, "%8s %d %d/%d/%d %d", VendorCode, &InStock, &Date.tm_mday, &Date.tm_mon, &Date.tm_year, &ShelfLife);
- Date.tm_mon--;
- Date.tm_year -= 1900;
- push(&(*head), VendorCode, InStock, Date, ShelfLife);
- }
- ifs.close();
- return 1;
- }
- // Запись в файл
- void fprint(const char *name, Stock *head)
- {
- std::ofstream ofs(name);
- Stock *last = head;
- do //Пока существует список
- {
- ofs << last->vendorCode << " " << last->inStock << " " << last->shelfLife << " " << std::put_time(&last->Date, "%d/%m/%Y") << std::endl;
- last = last->next; //Перевод указателя
- nl;
- } while (last != head);
- ofs.close();
- }
- // Чтение с консоли
- void scan(Stock **head)
- {
- char VendorCode[9]{};
- int InStock;
- std::tm Date = {};
- int ShelfLife;
- std::cout << "Введите артикул: ";
- std::cin >> VendorCode;
- nl;
- std::cout << "Введите сколько поступило на склад: ";
- std::cin >> InStock;
- nl;
- std::cout << "Введите дату поступлления на склад: ";
- std::cin >> std::get_time(&Date, "%d/%m/%Y");
- nl;
- std::cout << "Введите срок годности в часах: ";
- std::cin >> ShelfLife;
- nl;
- push(&(*head), VendorCode, InStock, Date, ShelfLife);
- }
- // Вывод на консоль.
- void print(Stock *head)
- {
- if (!head) return; //Если не существует списка - выходим
- Stock *last = head;
- do //Пока существует список
- {
- printf("%s ", last->vendorCode); //Вывод
- printf("%d ", last->inStock); //Вывод
- printf("%d ", last->shelfLife); //Вывод
- std::cout << std::put_time(&last->Date, "%d/%m/%Y");
- last = last->next; //Перевод указателя
- nl;
- } while (last != head);
- }
- // Удаление слишком новых записей
- void toDate(Stock **head, std::tm time)
- {
- Stock *current = (*head);
- int cout = 0;
- do
- {
- current = current->next;
- cout++;
- } while (current != *head);
- do
- {
- if (!timeCompare(time, 0, (*head)->Date))
- {
- pop(&(*head), (*head)->vendorCode);
- }
- else
- {
- *head = (*head)->next;
- }
- cout--;
- } while (cout != 0);
- }
- void Sort(Stock **head)
- {
- Stock *prev = nullptr;
- Stock *current = (*head);
- Stock *next = (*head)->next;
- int count = 0;
- do
- {
- prev = current;
- current = next;
- next = next->next;
- count++;
- } while (current != (*head));
- for (int i = 0; i < count; i++)
- {
- for(int j = 0; j < count - 1; j++)
- {
- if (!timeCompare((*head)->Date, 0, next->Date))
- {
- prev->next = next;
- (*head)->next = next->next;
- next->next = (*head);
- prev = next;
- next = (*head)->next;
- } else
- {
- prev = (*head);
- (*head) = next;
- next = next->next;
- }
- }
- print(*head);
- nl;
- }
- }
- // Анализ склада
- int analyze(Stock **stockList, Buy **buyList, std::tm time)
- {
- toDate(&(*stockList), time);
- while (buyList != nullptr)
- {
- if (!timeCompare(time, 0, (*buyList)->Date)) return 1;
- if (isEnought(&(*stockList), (*buyList)) == 1)
- {
- if (buy(&(*stockList), (*buyList)->vendorCode, (*buyList)->bought) == -1) return -1;
- }
- else return -1;
- (*buyList) = (*buyList)->next;
- }
- return 1;
- }
- int main()
- {
- setlocale(LC_ALL, "Russian");
- //system("chcp 65001");
- Stock *stockList = nullptr; //Создаем NULL-список склада
- Buy *buyList = nullptr; //Создает NULL-список покупок
- std::tm time = {};
- fscan("Stock.txt", &stockList);
- // Считывание и вывод склада
- fscan("Buy.txt", &buyList);
- // Считывание и вывод покупок
- char v = '1';
- bool b = true;//Переменная для switch
- bool o = false;
- while (true)
- {
- switch (v)
- {
- case '0':
- {
- b = false;
- break;
- }
- case '1':
- {
- printf("0. Выход\n1. Показать меню\n2. Покупки на склад\n3. Покупки со склада\n4. Анализ склада\n5. Ввод даты\n6. Добавить товар на склад\n7. Купить товар со склада\n8. Сортировка по времени\n");
- break;
- }
- case '2':
- {
- std::cout << "Покупки на склад: " << std::endl;
- print(stockList);
- nl;
- break;
- }
- case'3':
- {
- std::cout << "Покупки со склада: " << std::endl;
- print(buyList);
- nl;
- break;
- }
- case'4':
- {
- if (!o) break;
- std::cout << "Анализ склада на " << std::put_time(&time, "%d/%m/%Y") << ": " << std::endl;
- //Sort(&stocklist);
- //Sort(&buylist);
- analyze(&stockList, &buyList, time);
- print(stockList);
- fprint("Analyze.txt", stockList);
- nl;
- break;
- }
- case'5':
- {
- printf("Введите дату для анализа склада (дд/мм/гг): ");
- std::cin >> std::get_time(&time, "%d/%m/%Y");
- o = true;
- break;
- }
- case '6':
- {
- scan(&stockList);
- break;
- }
- case '7':
- {
- scan(&buyList);
- break;
- }
- case'8':
- {
- Sort(&stockList);
- break;
- }
- default:
- {
- printf("Ошибка ввода.\n");
- break;
- }
- }
- if (!b) break;
- std::cout << "Введите пункт меню: ";
- std::cin >> v;
- nl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement