Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "pch.h"
- #include <stdlib.h>
- #include <iostream>
- #include <vector>
- #include <string>
- #include <sstream>
- #include <windows.h>
- #include <stdio.h>
- #include <fstream>
- #include <cstdlib>
- #include <algorithm>
- #include <ctime>
- //_CRT_SECURE_NO_WARNINGS
- using namespace std;
- class date {
- int day;
- string month;
- int year;
- public:
- date() {
- srand(time(0));
- this->day = rand() % 31 + 1;
- this->month = to_string(rand() % 12 + 1);
- this->year = rand() % 50 + 1970;
- }
- date(int Day, string Month, int Year) {
- this->day = Day;
- this->month = Month;
- this->year = Year;
- }
- date(const date &d) {
- this->day = d.day;
- this->month = d.month;
- this->year = d.year;
- }
- string toString() {
- if (day< 10)
- return ("0"+to_string(day) + "." + month + "." + to_string(year));//01.01.2005
- else
- return (to_string(day) + "." + month + "." + to_string(year));
- }
- };
- class production
- {
- static int count; // счетчик количества записей в БД
- string company; // название компании
- string adr2; // адрес
- int type; //1-поставщик сырья, 2 - поставщик оборудования
- double balance; // сальдо
- date date_supply;
- public:
- production() //конструктор по умолчанию, вызываемый при добавлении записи
- {
- count++;
- this->company = "Default";
- this->adr2 = "Default";
- this->type = 1;
- this->balance = 0.0;
- this->date_supply = date();
- }
- production(string comp, string adrr, int type, double balanc, date DATE) //конструктор с параметрами, вызываемый при добавлении записи
- {
- count++;
- this->SetCompany(comp);
- this->SetAddress(adrr);
- this->SetType(type);
- this->SetBalance(balanc);
- this->SetDate(DATE);
- }
- production(string comp, string adrr, int type, double balanc, int day, string month, int year) //конструктор с параметрами, вызываемый при добавлении записи
- {
- count++;
- this->SetCompany(comp);
- this->SetAddress(adrr);
- this->SetType(type);
- this->SetBalance(balanc);
- this->SetDate(day,month,year);
- }
- production(const production &temp) {
- this->SetCompany(temp.company);
- this->SetAddress(temp.adr2);
- this->SetBalance(temp.balance);
- this->SetType(temp.type);
- this->SetDate(temp.date_supply)
- }
- //returnЫ для переменных
- int GetCount() {
- return count;
- }
- string GetCompany() {
- return company;
- }
- string GetAddress() {
- return adr2;
- }
- int GetType() {
- return type;
- }
- double GetBalance() {
- return balance;
- }
- date GetDate() {
- return this->date_supply;
- }
- //setЫ для переменных
- void SetCompany(string comp) {
- this->company = comp;
- }
- void SetAddress(string adrr) {
- this->adr2 = adrr;
- }
- void SetType(int typ) {
- this->type = typ;
- }
- void SetBalance(double balanse) {
- this->balance = balanse;
- }
- void SetDate(int day, string month, int year) {
- this->date_supply = date(day, month, year);
- }
- void SetDate(date d) {
- this->date_supply = d;
- }
- //переопределение метода то стринг
- string toString() {
- string buf = " ";//буфер пустого поля для company
- string bufadr = " "; //буфер пустого поля для address
- //вот это можно было сделать проще, но я хз как ( ятупой )
- char *buf2 = new char[1]; //буфер для типа
- _itoa(this->type, buf2, 10); //преобразование типа(инт) в чар
- string str(buf2); //пребразование чара в стринг
- buf2 = new char[20]; //буффер для сальдо
- sprintf(buf2, "%5.2f", this->balance); //преобразование дабл в чар
- string str2(buf2);//преобразование чар в стринг
- //
- string temp = company + buf.substr(0, (buf.length() - company.length())) + "|" + adr2 + bufadr.substr(0, (bufadr.length() - adr2.length())) + "| " + str + " |"+date_supply.toString()+"|" + str2; //складываем название + остаток пустой строки от буфера для названия + ... ( и так для каждого поля)
- return temp;
- }
- static vector<production> ReadFile(string AdrFile, vector<production> vec) {//функция считывания нашей бд из файла
- if (FileIsExist(AdrFile) == false) { // создать файл, если он не существует
- ofstream ofs(AdrFile);
- ofs.close();
- ofstream fout(AdrFile, ios_base::trunc); // удалить содержимое файла, если он существует
- if (!fout.is_open()) // если файл не открыт
- cout << "ERROR! File not open!" << endl; // сообщить об этом
- else
- fout << 0;
- fout.close();
- }
- ifstream fin(AdrFile); // открываем файл
- char buf[120]; // буфер для строки
- //считываем количество открывания базы
- fin.getline(buf, 130);
- char *countOpen = new char[1];
- countOpen[0] = buf[0];
- count = atoi(countOpen);
- //если она уже открывалась = значит не пустая, значит считываем
- if (count != 0) {
- while (1) {//беск цикл
- fin.getline(buf, 130); //считываем строку
- //буферы
- string company = "";
- string address = "";
- char* type = new char[1];
- char* balanse = new char[20];
- int i = 0;
- //преобразуем части считыной строки в наши части - сompany и т.д (я отсчитывал выделенное под каждое поле руками и запоминал значения - 16, 92, и т.д.)
- for (; i < 16; i++) company += buf[i];
- for (i = 17; i < 92; i++) address += buf[i];
- type[0] = buf[94];
- char* day = new char[2];
- char* year = new char[4];
- string month ="";
- while(buf[i] != '\0')
- {
- for(i = 100; i < 102; i++)
- day[i-100] = buf[i];
- while (buf[i] != '.') {
- month += buf[i];
- i++;
- }
- i++;
- int j = 0;
- while (buf[i] != '|') {
- year[j] += buf[i];
- i++;
- j++;
- }
- }
- for (int j = 0; i < 120; i++, j++) balanse[j] = buf[i];
- production temp = production(company, address, atoi(type), atof(balanse), atoi(day),month,atoi(year)); // создаем темповое значение из полученных частей
- vec.push_back(temp);//хапихиваем его в нашу бд
- if ((fin.get()) == EOF) // если следующий символ = символ конца файла
- {
- fin.close();//закрываем поток
- break;//останавливаем цикл
- }
- fin.seekg(-1, ios_base::cur); //если этот следующий символ != символу конца строки, возвращаем символ на 1, чтобы следующая строка считалась адекватно
- }
- }
- return vec;
- }
- static vector<production> add(vector<production> vec) { //Функция добавления записи в вектор продуктов
- //буферы
- string buf1, buf2;
- int typ = 1938567;
- double balance;
- cout << "4. #Initialized adding field" << endl;
- cout << "Enter name company: ";
- cin >> buf1;
- cin.get(); // чтобы очистить син как-то... не помню точно как
- cout << "Enter address: ";
- getline(cin, buf2); // чтобы ввести всю строку с пробелами (скажи прост загуглила так)
- cout << "Enter type of company (1 for material supplier, 2 for equipment supplier): "; // ввод типа, с проверкой на ввод херни
- do {
- if (typ != 1938567) { cout << endl << "ERROR! Enter 1 or 2!:"; } // если цикл еще раз сюда зашел, значит пользователь накосячил и надо вывести ошибку (типо значени по умолчанию изменилось, а в цикл еще раз зашли)
- cin >> typ;
- } while (typ != 1 && typ != 2);
- cout << "Enter balance: ";
- cin >> balance;
- production temp = production(buf1, buf2, typ, balance); // создаем темповое значение продукта
- vec.push_back(temp); // добавляем его в наш вектор
- return vec; //возвращаем наш вектор
- }
- friend int SearchByCompany(vector<production> vec);
- static int SearchByType(vector<production> vec)//поиск в бд по типу
- {
- if (vec.size() == 0) return 0;//если база пустая, сразу вернем 0
- int temp = 1938567;
- cout << "3. #Initialized Search By Type" << endl;
- cout << endl << "Enter type of company (1 for material supplier, 2 for equipment supplier): ";//проверка на ввод типа, аналогичная той, как выше в добавлении записи
- do {
- if (temp != 1938567) { cout << endl << "ERROR! Enter 1 or 2!:"; }
- cin >> temp;
- } while (temp != 1 && temp != 2);
- bool flag = false;//флаг того, что мы нашли нужную компанию
- cout << endl << " Name Company | Address | Type | Balance" << endl;// шапка
- for (int i = 0; i < vec.size(); i++) {
- if (vec[i].GetType() == temp) {
- cout << vec[i].toString() << endl;
- flag = true;
- }
- }
- if (flag == false)
- cout << "Company was not found!" << endl;
- return vec.size();
- }
- static vector<production> Sort(vector<production> vec)//сортировка по убыванию сальдо
- {
- production temp; // буфер
- for (int i = 0; i < vec.size(); i++) { //обычная пузырьковая сортировка по значению сальдо
- for (int j = 0; j < vec.size() - i - 1; j++) {
- if (vec[j].GetBalance() < vec[j + 1].GetBalance()) {
- temp = vec[j];
- vec[j] = vec[j + 1];
- vec[j + 1] = temp;
- }
- }
- }
- return vec;
- }
- static void exit(string AdrFile, vector<production> vec) { //функция выхода из программы
- if (FileIsExist(AdrFile) == false) { // создать файл, если он не существует
- ofstream ofs(AdrFile);
- if (!ofs.is_open()) // если файл не открыт
- cout << "ERROR! File not open!" << endl; // сообщить об этом
- else
- ofs << 0;
- ofs.close();
- }
- ifstream fin(AdrFile); // открываем файл
- char buf[120]; // буфер для строки
- //считываем количество открывания базы
- fin.getline(buf, 120);
- char *countOpen = new char[1];
- countOpen[0] = buf[0];
- int flagOpen = atoi(countOpen);
- fin.close();
- flagOpen++;
- ofstream fout(AdrFile, ios_base::trunc); // удалить содержимое файла, если он существует
- if (!fout.is_open()) // если файл не открыт
- cout << "ERROR! File not open!" << endl; // сообщить об этом
- else // если открыт
- {
- fout << to_string(flagOpen) + "\n";
- for (int i = 0; i < vec.size(); i++) // записать в него наш вектор
- fout << vec[i].toString() + "\n";
- }
- fout.close(); //и закрыть все нахер
- }
- ~production() { //деструктор (вызываемый при удалении записи)
- count--;
- }
- };
- int printTabl(vector<production> vec) { // Функция печати ветора таблицей
- if (vec.size() == 0) return 0;//если база пустая, сразу вернем 0
- cout << "1. #Initialized print base" << endl << endl;
- cout << " Name Company | Address | Type | Balance" << endl; // шапка
- for (int i = 0; i < vec.size(); i++) {
- cout << vec[i].toString() << endl;
- }
- return vec.size();
- }
- int SearchByCompany(vector<production> vec) //поиск в бд по названию компании
- {
- if (vec.size() == 0) return 0;//если база пустая, сразу вернем 0
- string temp;
- cout << "2. #Initialized Search By Company" << endl;
- cout << "Enter name of company for search: ";
- cin >> temp;
- bool flag = false; //флаг того, что мы нашли нужную компанию
- cout << endl << " Name Company | Address | Type | Balance" << endl;// шапка
- for (int i = 0; i < vec.size(); i++) {
- string str = vec[i].GetCompany();
- str.erase(remove(str.begin(), str.end(), ' '), str.end());
- if (str == temp) {
- cout << vec[i].toString() << endl;
- flag = true;
- }
- }
- if (flag == false)
- cout << "Company was not found!" << endl;
- return vec.size();
- }
- bool FileIsExist(string filePath) // функция поиска файла
- {
- bool isExist = false; // флаг того, что мы нашли
- ifstream fin(filePath.c_str()); //открываем файл
- if (fin.is_open()) //если открылся
- isExist = true; // то заебись
- fin.close(); // закрыли поток
- return isExist; //вернули флаг
- }
- int main()
- {
- string str = "D:\\proba\\text.txt";
- vector<production> vec = production::ReadFile(str, vec); //при запуске программы сразу считываем базу из файла
- //меню
- int select = 0;
- while (select != -1) {
- switch (select)
- {
- case 0: {
- cout << " MENU " << endl;
- cout << "1. Print base" << endl;
- cout << "2. Search by company" << endl;
- cout << "3. Search by type" << endl;
- cout << "4. Adding reccord" << endl;
- cout << "5. Sorting for balance" << endl;
- cout << "6. DEMO : add test record to base" << endl;
- cout << "7. Save and exit" << endl;
- cout << "Enter case of menu:" << endl;
- while (!(cin >> select)) //обработка ввода только интов
- {
- cin.clear();
- while (cin.get() != '\n');
- cout << "Error! Enter int!: ";
- }
- system("cls"); //очистка консоли
- break;
- }
- case 1: {
- if (printTabl(vec) == 0) cout << "Base is empty!" << endl; //вызов функции печати таблица, если вернула 0 - значит таблица пустая
- select = 100; //переключатель в окно выброса диалога дальнейшего действия (везде такой)
- break;
- }
- case 2: {
- if (SearchByCompany(vec) == 0) cout << "Base is empty!" << endl; //вызов функции поиска по компании, если вернула 0 - значит таблица пустая
- select = 100;
- break;
- }
- case 3: {
- if (production::SearchByType(vec) == 0) cout << "Base is empty!" << endl; //вызов функции поиска по типу, если вернула 0 - значит таблица пустая
- select = 100;
- break;
- }
- case 4: {
- vec = production::add(vec); //вызов функции добавления записи
- select = 100;
- break;
- }
- case 5: {
- cout << "5. #Initialized Sotring for balanxe" << endl;
- cout << endl << "*** Before sorting:" << endl;
- if (printTabl(vec) == 0) cout << "Base is empty!" << endl;//вызов функции печати таблица, если вернула 0 - значит таблица пустая
- vec = production::Sort(vec); //сортировка по убыванию сальдо
- cout << endl << "*** After sotring:" << endl;
- if (printTabl(vec) == 0) cout << "Base is empty!" << endl;//вызов функции печати таблица, если вернула 0 - значит таблица пустая
- select = 100;
- break;
- }
- case 6: {
- cout << "6. #Initialized DEMO : add test record to base" << endl; //добавить в базу несколько значений для теста
- production* prod = new production[3];
- prod[0] = production("MIET", "KOrobro 16", 1, 135.7);
- prod[1] = production("Porshe", "Rikwkwfwf 116", 2, 13665.7);
- prod[2] = production("wre", "121 16", 1, 1.7);
- for (int i = 0; i < 3; i++) vec.push_back(prod[i]);
- cout << endl << "Records added successfully!!! )))" << endl;
- select = 100;
- break;
- }
- case 7: { //сохранение базы и выход
- production::exit(str, vec);
- select = -1;
- break;
- }
- case 100: {
- cout << endl << "If you want exit to menu - enter 0 | If you want exit from programm - enter 7 :"; //окно выброса диалога дальнейшего действия(везде такой)
- select = 1938567;
- do {
- if (select != 1938567) { cout << endl << "ERROR! Enter 0 or 7!:"; } // если цикл еще раз сюда зашел, значит пользователь накосячил и надо вывести ошибку (типо значени по умолчанию изменилось, а в цикл еще раз зашли)
- while (!(cin >> select)) //проверка на целое число
- {
- cin.clear();
- while (cin.get() != '\n');
- cout << "Error! Enter int!: ";
- }
- } while (select != 7 && select != 0); //проверка на определенное! целое число
- system("cls");
- break;
- }
- default: //если мы ввели какой-то косой инт в меню
- cout << endl << "ERROR! If you want exit to menu - enter 0 | If you want exit from programm - enter 7 :";
- select = 1938567;
- do {
- if (select != 1938567) { cout << endl << "ERROR! Enter 0 or 7!:"; } // если цикл еще раз сюда зашел, значит пользователь накосячил и надо вывести ошибку (типо значени по умолчанию изменилось, а в цикл еще раз зашли)
- while (!(cin >> select))
- {
- cin.clear();
- while (cin.get() != '\n');
- cout << "Error! Enter int!: ";
- }
- } while (select != 7 && select != 0);
- system("cls");
- break;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement