Advertisement
Guest User

Untitled

a guest
Oct 11th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 18.42 KB | None | 0 0
  1. #include "pch.h"
  2. #include <stdlib.h>
  3. #include <iostream>
  4. #include <vector>
  5. #include <string>
  6. #include <sstream>
  7. #include <windows.h>
  8. #include <stdio.h>
  9. #include <fstream>
  10. #include <cstdlib>
  11. #include <algorithm>
  12. #include <ctime>
  13. //_CRT_SECURE_NO_WARNINGS
  14.  
  15. using namespace std;
  16. class date {
  17.     int day;
  18.     string month;
  19.     int year;
  20. public:
  21.     date() {
  22.         srand(time(0));
  23.         this->day = rand() % 31 + 1;
  24.         this->month = to_string(rand() % 12 + 1);
  25.         this->year = rand() % 50 + 1970;
  26.     }
  27.     date(int Day, string Month, int Year) {
  28.         this->day = Day;
  29.         this->month = Month;
  30.         this->year = Year;
  31.     }
  32.     date(const date &d) {
  33.         this->day = d.day;
  34.         this->month = d.month;
  35.         this->year = d.year;
  36.     }
  37.     string toString() {
  38.         if (day< 10)
  39.             return ("0"+to_string(day)  + "." + month + "." + to_string(year));//01.01.2005
  40.         else
  41.             return (to_string(day) + "." + month + "." + to_string(year));
  42.  
  43.     }
  44. };
  45. class production
  46. {
  47.     static int count; // счетчик количества записей в БД
  48.     string company; // название компании
  49.     string adr2; // адрес
  50.     int type;   //1-поставщик сырья, 2 - поставщик оборудования
  51.     double balance; // сальдо
  52.     date date_supply;
  53.  
  54. public:
  55.     production() //конструктор по умолчанию, вызываемый при добавлении записи
  56.     {
  57.         count++;
  58.         this->company = "Default";
  59.         this->adr2 = "Default";
  60.         this->type = 1;
  61.         this->balance = 0.0;
  62.         this->date_supply = date();
  63.     }
  64.     production(string comp, string adrr, int type, double balanc, date DATE) //конструктор с параметрами, вызываемый при добавлении записи
  65.     {
  66.         count++;
  67.         this->SetCompany(comp);
  68.         this->SetAddress(adrr);
  69.         this->SetType(type);
  70.         this->SetBalance(balanc);
  71.         this->SetDate(DATE);
  72.     }
  73.     production(string comp, string adrr, int type, double balanc, int day, string month, int year) //конструктор с параметрами, вызываемый при добавлении записи
  74.     {
  75.         count++;
  76.         this->SetCompany(comp);
  77.         this->SetAddress(adrr);
  78.         this->SetType(type);
  79.         this->SetBalance(balanc);
  80.         this->SetDate(day,month,year);
  81.     }
  82.     production(const production &temp) {
  83.         this->SetCompany(temp.company);
  84.         this->SetAddress(temp.adr2);
  85.         this->SetBalance(temp.balance);
  86.         this->SetType(temp.type);
  87.         this->SetDate(temp.date_supply)
  88.  
  89.     }
  90.     //returnЫ для переменных
  91.     int GetCount() {
  92.         return count;
  93.     }
  94.     string GetCompany() {
  95.         return company;
  96.     }
  97.     string GetAddress() {
  98.         return adr2;
  99.     }
  100.     int GetType() {
  101.         return type;
  102.     }
  103.     double GetBalance() {
  104.         return balance;
  105.     }
  106.     date GetDate() {
  107.         return this->date_supply;
  108.     }
  109.     //setЫ для переменных
  110.     void SetCompany(string comp) {
  111.         this->company = comp;
  112.     }
  113.     void SetAddress(string adrr) {
  114.         this->adr2 = adrr;
  115.     }
  116.     void SetType(int typ) {
  117.         this->type = typ;
  118.     }
  119.     void SetBalance(double balanse) {
  120.         this->balance = balanse;
  121.     }
  122.     void SetDate(int day, string month, int year) {
  123.         this->date_supply = date(day, month, year);
  124.     }
  125.     void SetDate(date d) {
  126.         this->date_supply = d;
  127.     }
  128.     //переопределение метода то стринг
  129.     string toString() {
  130.         string buf = "                ";//буфер пустого поля для company
  131.         string bufadr = "                                                                           "; //буфер пустого поля для address
  132.  
  133.         //вот это можно было сделать проще, но я хз как ( ятупой )
  134.         char *buf2 = new char[1]; //буфер для типа
  135.         _itoa(this->type, buf2, 10); //преобразование типа(инт) в чар
  136.         string str(buf2); //пребразование чара в стринг
  137.         buf2 = new char[20]; //буффер для сальдо
  138.         sprintf(buf2, "%5.2f", this->balance); //преобразование дабл в чар
  139.         string str2(buf2);//преобразование чар в стринг
  140.         //
  141.  
  142.         string temp = company + buf.substr(0, (buf.length() - company.length())) + "|" + adr2 + bufadr.substr(0, (bufadr.length() - adr2.length())) + "| " + str + "    |"+date_supply.toString()+"|" + str2; //складываем название + остаток пустой строки от буфера для названия + ... ( и так для каждого поля)
  143.  
  144.         return temp;
  145.     }
  146.     static vector<production> ReadFile(string AdrFile, vector<production> vec) {//функция считывания нашей бд из файла
  147.         if (FileIsExist(AdrFile) == false) { // создать файл, если он не существует
  148.             ofstream ofs(AdrFile);
  149.             ofs.close();
  150.             ofstream fout(AdrFile, ios_base::trunc); // удалить содержимое файла, если он существует
  151.             if (!fout.is_open()) // если файл не открыт
  152.                 cout << "ERROR! File not open!" << endl; // сообщить об этом
  153.             else
  154.                 fout << 0;
  155.             fout.close();
  156.         }
  157.         ifstream fin(AdrFile); // открываем файл
  158.         char buf[120]; // буфер для строки
  159.  
  160.         //считываем количество открывания базы
  161.         fin.getline(buf, 130);
  162.         char *countOpen = new char[1];
  163.         countOpen[0] = buf[0];
  164.         count = atoi(countOpen);
  165.  
  166.         //если она уже открывалась = значит не пустая, значит считываем
  167.         if (count != 0) {
  168.             while (1) {//беск цикл
  169.                 fin.getline(buf, 130); //считываем строку
  170.  
  171.                 //буферы
  172.                 string company = "";
  173.                 string address = "";
  174.                 char* type = new char[1];
  175.                 char* balanse = new char[20];
  176.                 int i = 0;
  177.                 //преобразуем части считыной строки в наши части - сompany и т.д (я отсчитывал выделенное под каждое поле руками и запоминал значения - 16, 92, и т.д.)
  178.                 for (; i < 16; i++) company += buf[i];
  179.                 for (i = 17; i < 92; i++) address += buf[i];
  180.                 type[0] = buf[94];
  181.                 char* day = new char[2];
  182.                 char* year = new char[4];
  183.                 string month ="";
  184.  
  185.                 while(buf[i] != '\0')
  186.                 {
  187.  
  188.                         for(i = 100; i < 102; i++)
  189.                             day[i-100] = buf[i];
  190.  
  191.                         while (buf[i] != '.') {
  192.                             month += buf[i];
  193.                             i++;
  194.                         }
  195.                         i++;
  196.                         int j = 0;
  197.                         while (buf[i] != '|') {
  198.                             year[j] += buf[i];
  199.                             i++;
  200.                             j++;
  201.                         }
  202.    
  203.                 }
  204.                 for (int j = 0; i < 120; i++, j++) balanse[j] = buf[i];
  205.  
  206.                 production temp = production(company, address, atoi(type), atof(balanse), atoi(day),month,atoi(year)); // создаем темповое значение из полученных частей
  207.                 vec.push_back(temp);//хапихиваем его в нашу бд
  208.  
  209.                 if ((fin.get()) == EOF) // если следующий символ = символ конца файла
  210.                 {
  211.                     fin.close();//закрываем поток
  212.                     break;//останавливаем цикл
  213.                 }
  214.                 fin.seekg(-1, ios_base::cur); //если этот следующий символ != символу конца строки, возвращаем символ на 1, чтобы следующая строка считалась адекватно
  215.             }
  216.         }
  217.         return vec;
  218.     }
  219.     static vector<production> add(vector<production> vec) { //Функция добавления записи в вектор продуктов
  220.     //буферы
  221.         string buf1, buf2;
  222.         int typ = 1938567;
  223.         double balance;
  224.  
  225.         cout << "4. #Initialized adding field" << endl;
  226.         cout << "Enter name company: ";
  227.         cin >> buf1;
  228.  
  229.         cin.get(); // чтобы очистить син как-то... не помню точно как
  230.         cout << "Enter address: ";
  231.         getline(cin, buf2); // чтобы ввести всю строку с пробелами (скажи прост загуглила так)
  232.  
  233.         cout << "Enter type of company (1 for material supplier, 2 for equipment supplier): "; // ввод типа, с проверкой на ввод херни
  234.         do {
  235.             if (typ != 1938567) { cout << endl << "ERROR! Enter 1 or 2!:"; } // если цикл еще раз сюда зашел, значит пользователь накосячил и надо вывести ошибку (типо значени по умолчанию изменилось, а в цикл еще раз зашли)
  236.             cin >> typ;
  237.         } while (typ != 1 && typ != 2);
  238.  
  239.         cout << "Enter balance: ";
  240.         cin >> balance;
  241.  
  242.         production temp = production(buf1, buf2, typ, balance); // создаем темповое значение продукта
  243.         vec.push_back(temp); // добавляем его в наш вектор
  244.         return vec; //возвращаем наш вектор
  245.     }
  246.     friend int SearchByCompany(vector<production> vec);
  247.     static int SearchByType(vector<production> vec)//поиск в бд по типу
  248.     {
  249.         if (vec.size() == 0) return 0;//если база пустая, сразу вернем 0
  250.         int temp = 1938567;
  251.         cout << "3. #Initialized Search By Type" << endl;
  252.  
  253.         cout << endl << "Enter type of company (1 for material supplier, 2 for equipment supplier): ";//проверка на ввод типа, аналогичная той, как выше в добавлении записи
  254.         do {
  255.             if (temp != 1938567) { cout << endl << "ERROR! Enter 1 or 2!:"; }
  256.             cin >> temp;
  257.         } while (temp != 1 && temp != 2);
  258.  
  259.         bool flag = false;//флаг того, что мы нашли нужную компанию
  260.         cout << endl << "  Name Company  |                                  Address                                  | Type | Balance" << endl;// шапка
  261.         for (int i = 0; i < vec.size(); i++) {
  262.             if (vec[i].GetType() == temp) {
  263.                 cout << vec[i].toString() << endl;
  264.                 flag = true;
  265.             }
  266.         }
  267.         if (flag == false)
  268.             cout << "Company was not found!" << endl;
  269.         return vec.size();
  270.     }
  271.     static vector<production> Sort(vector<production> vec)//сортировка по убыванию сальдо
  272.     {
  273.         production temp; // буфер
  274.         for (int i = 0; i < vec.size(); i++) { //обычная пузырьковая сортировка по значению сальдо
  275.             for (int j = 0; j < vec.size() - i - 1; j++) {
  276.                 if (vec[j].GetBalance() < vec[j + 1].GetBalance()) {
  277.                     temp = vec[j];
  278.                     vec[j] = vec[j + 1];
  279.                     vec[j + 1] = temp;
  280.                 }
  281.             }
  282.         }
  283.         return vec;
  284.     }
  285.     static void exit(string AdrFile, vector<production> vec) { //функция выхода из программы
  286.         if (FileIsExist(AdrFile) == false) { // создать файл, если он не существует
  287.             ofstream ofs(AdrFile);
  288.             if (!ofs.is_open()) // если файл не открыт
  289.                 cout << "ERROR! File not open!" << endl; // сообщить об этом
  290.             else
  291.                 ofs << 0;
  292.             ofs.close();
  293.         }
  294.         ifstream fin(AdrFile); // открываем файл
  295.         char buf[120]; // буфер для строки
  296.  
  297.         //считываем количество открывания базы
  298.         fin.getline(buf, 120);
  299.         char *countOpen = new char[1];
  300.         countOpen[0] = buf[0];
  301.         int flagOpen = atoi(countOpen);
  302.         fin.close();
  303.         flagOpen++;
  304.  
  305.         ofstream fout(AdrFile, ios_base::trunc); // удалить содержимое файла, если он существует
  306.         if (!fout.is_open()) // если файл не открыт
  307.             cout << "ERROR! File not open!" << endl; // сообщить об этом
  308.         else // если открыт
  309.         {
  310.             fout << to_string(flagOpen) + "\n";
  311.             for (int i = 0; i < vec.size(); i++) // записать в него наш вектор
  312.                 fout << vec[i].toString() + "\n";
  313.         }
  314.         fout.close(); //и закрыть все нахер
  315.     }
  316.     ~production() { //деструктор (вызываемый при удалении записи)
  317.         count--;
  318.     }
  319. };
  320.  
  321. int printTabl(vector<production> vec) { // Функция печати ветора таблицей
  322.     if (vec.size() == 0) return 0;//если база пустая, сразу вернем 0
  323.     cout << "1. #Initialized print base" << endl << endl;
  324.     cout << "  Name Company  |                                  Address                                  | Type | Balance" << endl; // шапка
  325.     for (int i = 0; i < vec.size(); i++) {
  326.         cout << vec[i].toString() << endl;
  327.     }
  328.     return vec.size();
  329. }
  330.  
  331. int SearchByCompany(vector<production> vec) //поиск в бд по названию компании
  332. {
  333.     if (vec.size() == 0) return 0;//если база пустая, сразу вернем 0
  334.     string temp;
  335.     cout << "2. #Initialized Search By Company" << endl;
  336.     cout << "Enter name of company for search: ";
  337.     cin >> temp;
  338.     bool flag = false; //флаг того, что мы нашли нужную компанию
  339.     cout << endl << "  Name Company  |                                  Address                                  | Type | Balance" << endl;// шапка
  340.     for (int i = 0; i < vec.size(); i++) {
  341.         string str = vec[i].GetCompany();
  342.         str.erase(remove(str.begin(), str.end(), ' '), str.end());
  343.         if (str == temp) {
  344.  
  345.             cout << vec[i].toString() << endl;
  346.             flag = true;
  347.         }
  348.     }
  349.     if (flag == false)
  350.         cout << "Company was not found!" << endl;
  351.     return vec.size();
  352. }
  353.  
  354.  
  355.  
  356. bool FileIsExist(string filePath) // функция поиска файла
  357. {
  358.     bool isExist = false; // флаг того, что мы нашли
  359.     ifstream fin(filePath.c_str()); //открываем файл
  360.  
  361.     if (fin.is_open()) //если открылся
  362.         isExist = true; // то заебись
  363.  
  364.     fin.close(); // закрыли поток
  365.     return isExist; //вернули флаг
  366. }
  367.  
  368.  
  369.  
  370.  
  371. int main()
  372. {
  373.     string str = "D:\\proba\\text.txt";
  374.     vector<production> vec = production::ReadFile(str, vec); //при запуске программы сразу считываем базу из файла
  375.  
  376.     //меню
  377.     int select = 0;
  378.     while (select != -1) {
  379.  
  380.  
  381.  
  382.         switch (select)
  383.         {
  384.         case 0: {
  385.             cout << "         MENU         " << endl;
  386.             cout << "1. Print base" << endl;
  387.             cout << "2. Search by company" << endl;
  388.             cout << "3. Search by type" << endl;
  389.             cout << "4. Adding reccord" << endl;
  390.             cout << "5. Sorting for balance" << endl;
  391.             cout << "6. DEMO : add test record to base" << endl;
  392.             cout << "7. Save and exit" << endl;
  393.             cout << "Enter case of menu:" << endl;
  394.             while (!(cin >> select)) //обработка ввода только интов
  395.             {
  396.                 cin.clear();
  397.                 while (cin.get() != '\n');
  398.  
  399.                 cout << "Error! Enter int!: ";
  400.             }
  401.             system("cls"); //очистка консоли
  402.             break;
  403.         }
  404.         case 1: {
  405.             if (printTabl(vec) == 0) cout << "Base is empty!" << endl; //вызов функции печати таблица, если вернула 0 - значит таблица пустая
  406.             select = 100; //переключатель в окно выброса диалога дальнейшего действия (везде такой)
  407.             break;
  408.         }
  409.         case 2: {
  410.             if (SearchByCompany(vec) == 0) cout << "Base is empty!" << endl; //вызов функции поиска по компании, если вернула 0 - значит таблица пустая
  411.             select = 100;
  412.             break;
  413.         }
  414.         case 3: {
  415.             if (production::SearchByType(vec) == 0) cout << "Base is empty!" << endl; //вызов функции поиска по типу, если вернула 0 - значит таблица пустая
  416.             select = 100;
  417.             break;
  418.         }
  419.         case 4: {
  420.             vec = production::add(vec); //вызов функции добавления записи
  421.             select = 100;
  422.             break;
  423.         }
  424.         case 5: {
  425.             cout << "5. #Initialized Sotring for balanxe" << endl;
  426.             cout << endl << "*** Before sorting:" << endl;
  427.             if (printTabl(vec) == 0) cout << "Base is empty!" << endl;//вызов функции печати таблица, если вернула 0 - значит таблица пустая
  428.  
  429.             vec = production::Sort(vec); //сортировка по убыванию сальдо
  430.  
  431.             cout << endl << "*** After sotring:" << endl;
  432.             if (printTabl(vec) == 0) cout << "Base is empty!" << endl;//вызов функции печати таблица, если вернула 0 - значит таблица пустая
  433.             select = 100;
  434.             break;
  435.         }
  436.         case 6: {
  437.             cout << "6. #Initialized DEMO : add test record to base" << endl; //добавить в базу несколько значений для теста
  438.             production* prod = new production[3];
  439.             prod[0] = production("MIET", "KOrobro 16", 1, 135.7);
  440.             prod[1] = production("Porshe", "Rikwkwfwf 116", 2, 13665.7);
  441.             prod[2] = production("wre", "121 16", 1, 1.7);
  442.             for (int i = 0; i < 3; i++) vec.push_back(prod[i]);
  443.             cout << endl << "Records added successfully!!! )))" << endl;
  444.             select = 100;
  445.             break;
  446.         }
  447.         case 7: { //сохранение базы и выход
  448.             production::exit(str, vec);
  449.             select = -1;
  450.             break;
  451.         }
  452.         case 100: {
  453.             cout << endl << "If you want exit to menu - enter 0 | If you want exit from programm - enter 7 :"; //окно выброса диалога дальнейшего действия(везде такой)
  454.             select = 1938567;
  455.             do {
  456.                 if (select != 1938567) { cout << endl << "ERROR! Enter 0 or 7!:"; } // если цикл еще раз сюда зашел, значит пользователь накосячил и надо вывести ошибку (типо значени по умолчанию изменилось, а в цикл еще раз зашли)
  457.                 while (!(cin >> select)) //проверка на целое число
  458.                 {
  459.                     cin.clear();
  460.                     while (cin.get() != '\n');
  461.  
  462.                     cout << "Error! Enter int!: ";
  463.                 }
  464.             } while (select != 7 && select != 0); //проверка на определенное! целое число
  465.             system("cls");
  466.             break;
  467.         }
  468.         default: //если мы ввели какой-то косой инт в меню
  469.             cout << endl << "ERROR! If you want exit to menu - enter 0 | If you want exit from programm - enter 7 :";
  470.             select = 1938567;
  471.             do {
  472.                 if (select != 1938567) { cout << endl << "ERROR! Enter 0 or 7!:"; } // если цикл еще раз сюда зашел, значит пользователь накосячил и надо вывести ошибку (типо значени по умолчанию изменилось, а в цикл еще раз зашли)
  473.                 while (!(cin >> select))
  474.                 {
  475.                     cin.clear();
  476.                     while (cin.get() != '\n');
  477.  
  478.                     cout << "Error! Enter int!: ";
  479.                 }
  480.             } while (select != 7 && select != 0);
  481.             system("cls");
  482.             break;
  483.         }
  484.     }
  485.     return 0;
  486. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement