Advertisement
Alyks

Untitled

Mar 22nd, 2020
445
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 17.17 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <fstream>
  5. #include <cstring>
  6.  
  7. using namespace std;
  8.  
  9. struct Employee {
  10. public:
  11.     char surname[20];
  12.     char department[20];
  13.     double salary;
  14.  
  15.     Employee() {
  16.         strcpy(surname, "");
  17.         strcpy(department, "");
  18.         salary = 0;
  19.     }
  20.  
  21.     Employee(char surname[20], char department[20], double salary) {
  22.         strcpy(this->surname, surname);
  23.         strcpy(this->department, department);
  24.         this->salary = salary;
  25.     }
  26. };
  27.  
  28. struct DepartmentData {
  29. public:
  30.     string name;
  31.     double sum = 0;
  32.  
  33.     DepartmentData(string name, double sum) {
  34.         this->name = name;
  35.         this->sum = sum;
  36.     }
  37. };
  38.  
  39. void executeAction(string action);
  40.  
  41. void showInfo() {
  42.     cout << "Выберите, что вы хотите сделать (введите в консоль значение из квадратных скобок):" << endl;
  43.     cout << "| Добавить сотрудников [доб] | Изменить данные сотрудников [изм] | Удалить сотрудников [уд] | Вывести информацию о сотрудниках на экран [выв] | Вывести сумму выплат по отделам за месяц [сум] | Завершить работу программы [выход] |" << endl;
  44. }
  45.  
  46. string chooseAction() {
  47.     vector<string> actions = {"доб", "изм", "уд", "выв", "сум", "выход"};
  48.     string choice;
  49.     getline(cin, choice);
  50.     while(find(actions.begin(), actions.end(), choice) == actions.end()) {
  51.         cout << "Вы должны выбрать существующее действие." << endl;
  52.         getline(cin, choice);
  53.     }
  54.     return choice;
  55. }
  56.  
  57. void showArr(vector<Employee> data) {
  58.     for(int i = 0; i < data.size(); i++) {
  59.         Employee emp = data[i];
  60.         cout << "Сотрудник №" << (i+1) << endl;
  61.         cout << "Фамилия: " << emp.surname << endl;
  62.         cout << "Наименование отдела: " << emp.department << endl;
  63.         cout << "Заработная плата: " << emp.salary << '\n' << endl;
  64.     }
  65. }
  66.  
  67. vector<Employee> grabData(bool show, string *fp = nullptr) {
  68.     string filePath;
  69.     if(fp == nullptr) {
  70.         cout << "Введите имя файла" << endl;
  71.         getline(cin, filePath);
  72.         filePath += ".dat";
  73.     } else
  74.         filePath = *fp;
  75.     vector<Employee> data;
  76.     ifstream is(filePath);
  77.     if(is.good()) {
  78.         Employee temp;
  79.         while(is.read((char*)&temp, sizeof(Employee))) {
  80.             Employee emp(temp.surname, temp.department, temp.salary);
  81.             data.push_back(emp);
  82.         }
  83.         if(show) {
  84.             if(data.size() > 0) {
  85.                 cout << "Данные, записанные в файле:" << endl;
  86.                 showArr(data);
  87.             } else
  88.                 cout << "В файле не найдено ни одной записи" << endl;
  89.         }
  90.     } else
  91.         cout << "Произошла ошибка при чтении файла. Убедитесь, что такой файл существует." << endl;
  92.     is.close();
  93.     return data;
  94. }
  95.  
  96. void createNewFile(vector<Employee> data, string filePath) {
  97.     ofstream os(filePath, ifstream::binary);
  98.     if(os.is_open()) {
  99.         for(Employee emp : data)
  100.             os.write((char*)&emp, sizeof(Employee));
  101.         cout << "Данные успешно сохранены в файл " << filePath << endl;
  102.     } else {
  103.         cout << "Не удалось сохранить данные в файл." << endl;
  104.     }
  105.     os.close();
  106. }
  107.  
  108. void updateFile(vector<Employee> newData, string filePath) {
  109.     vector<Employee> data = grabData(false, &filePath);
  110.     data.insert(data.end(), newData.begin(), newData.end());
  111.     ofstream os(filePath, ifstream::binary);
  112.     if(os.is_open()) {
  113.         for(Employee emp : data)
  114.             os.write((char*)&emp, sizeof(Employee));
  115.         cout << "Данные успешно обновлены в файле " << filePath << endl;
  116.     } else {
  117.         cout << "Не удалось сохранить данные в файл." << endl;
  118.     }
  119.     os.close();
  120. }
  121.  
  122. void saveDataToFile(vector<Employee> data, bool update) {
  123.     cout << "Введите [д], если хотите сохранить данные в файл." << endl;
  124.     string choice;
  125.     getline(cin, choice);
  126.     if(choice == "д") {
  127.         cout << "Введите имя файла" << endl;
  128.         string filePath;
  129.         getline(cin, filePath);
  130.         filePath += ".dat";
  131.         ifstream file (filePath);
  132.         if(update && file.good()) {
  133.             cout << "Файл с таким именем уже существует. Хотите его обновить? [д/н] (При выборе [н] создастся новый файл)" << endl;
  134.             getline(cin, choice);
  135.             if(choice == "д")
  136.                 updateFile(data, filePath);
  137.             else
  138.                 createNewFile(data, filePath);
  139.         } else
  140.             createNewFile(data, filePath);
  141.     }
  142. }
  143.  
  144. void addData() {
  145.     vector<Employee> data;
  146.     bool continueCycle = true;
  147.     bool notCorrect = true;
  148.     cout << "Если хотите прекратить ввод, введите [стоп] вместо фамилии сотрудника" << endl;
  149.     while(continueCycle) {
  150.         char surname[20];
  151.         char department[20];
  152.         double salary = 0;
  153.         while(notCorrect) {
  154.             cout << "Введите фамилию сотрудника" << endl;
  155.             cin.getline(surname, 20);
  156.             if(surname[0] != '\0') {
  157.                 if(strcmp(surname, "стоп") == 0) {
  158.                     continueCycle = false;
  159.                     notCorrect = false;
  160.                 } else {
  161.                     cout << "Введите название отдела" << endl;
  162.                     cin.getline(department, 20);
  163.                     if(department[0] != '\0') {
  164.                         cout << "Введите заработную плату сотрудника" << endl;
  165.                         string str;
  166.                         getline(cin, str);
  167.                         try {
  168.                             salary = stod(str);
  169.                             if(salary > -1)
  170.                                 notCorrect = false;
  171.                             else {
  172.                                 notCorrect = true;
  173.                                 cout << "Заработная плата не может быть отрицательной, повторите ввод" << endl;
  174.                             }
  175.                         } catch(...) {
  176.                             notCorrect = true;
  177.                             cout << "Возникла ошибка при вводе данных, повторите ввод." << endl;
  178.                         }
  179.                     } else
  180.                         cout << "Название отдела не может быть пустым, повторите ввод." << endl;
  181.                 }
  182.             } else
  183.                 cout << "Фамилия не может быть пустой, повторите ввод." << endl;
  184.         }
  185.         if(strcmp(surname, "стоп") != 0) {
  186.             notCorrect = true;
  187.             data.push_back(*new Employee(surname, department, salary));
  188.         }
  189.     }
  190.     saveDataToFile(data, true);
  191.     showInfo();
  192.     executeAction(chooseAction());
  193. }
  194.  
  195. string makeChoice(vector<string> choices) {
  196.     string choice = "";
  197.     while(find(choices.begin(), choices.end(), choice) == choices.end()) {
  198.         cout << "Введите либо [д], либо [н]" << endl;
  199.         getline(cin, choice);
  200.     }
  201.     return choice;
  202. }
  203.  
  204. int changeEmployeeData(Employee *emp, int changes) {
  205.     cin.clear();
  206.     string choice = "";
  207.     bool notCorrect = true;
  208.     vector<string> choices = {"д", "н"};
  209.     while(notCorrect) {
  210.         cout << "Хотите изменить фамилию?" << endl;
  211.         choice = makeChoice(choices);
  212.         if (choice == "д") {
  213.             cout << "Введите новую фамилию" << endl;
  214.             char surname[20];
  215.             cin.getline(surname, 20);
  216.             if(surname[0] != '\0') {
  217.                 strcpy(emp->surname, surname);
  218.                 cout << "Фамилия успешно изменена, хотите продолжить изменение данных?" << endl;
  219.                 notCorrect = false;
  220.                 changes++;
  221.                 choice = makeChoice(choices);
  222.                 if (choice == "д")
  223.                     changeEmployeeData(emp, changes);
  224.             } else
  225.                 cout << "Фамилия не может быть пустой, повторите ввод." << endl;
  226.         } else {
  227.             cout << "Хотите изменить наименование отдела?" << endl;
  228.             choice = makeChoice(choices);
  229.             if (choice == "д") {
  230.                 cout << "Введите наименование отдела" << endl;
  231.                 char department[20];
  232.                 cin.getline(department, 20);
  233.                 if(department[0] != '\0') {
  234.                     strcpy(emp->department, department);
  235.                     cout << "Наименование отдела успешно изменено, хотите продолжить изменение данных?" << endl;
  236.                     notCorrect = false;
  237.                     changes++;
  238.                     choice = makeChoice(choices);
  239.                     if (choice == "д")
  240.                         changeEmployeeData(emp, changes);
  241.                 } else
  242.                     cout << "Название отдела не может быть пустым, повторите ввод." << endl;
  243.             } else {
  244.                 cout << "Хотите изменить размер заработной платы?" << endl;
  245.                 choice = makeChoice(choices);
  246.                 if (choice == "д") {
  247.                     cout << "Введите размер заработной платы" << endl;
  248.                     double salary;
  249.                     string str;
  250.                     try {
  251.                         getline(cin, str);
  252.                         salary = stod(str);
  253.                         if (salary > -1) {
  254.                             notCorrect = false;
  255.                             emp->salary = salary;
  256.                             cout << "Заработная плата успешно изменена" << endl;
  257.                             changes++;
  258.                         } else {
  259.                             notCorrect = true;
  260.                             cout << "Заработная плата не может быть отрицательной, повторите ввод" << endl;
  261.                         }
  262.                     } catch (...) {
  263.                         cout << "Заработная плата должна быть числом" << endl;
  264.                     }
  265.                 }
  266.             }
  267.         }
  268.     }
  269.     return changes;
  270. }
  271.  
  272. void changeData() {
  273.     vector<Employee> data = grabData(true);
  274.     if(data.size() > 0) {
  275.         bool continueCycle = true;
  276.         bool notCorrect = true;
  277.         int changedCount = 0;
  278.         while(continueCycle) {
  279.             cout << "Введите номер сотрудника, данные которого хотите изменить, либо [стоп], чтобы вернуться в меню" << endl;
  280.             while(notCorrect) {
  281.                 string input;
  282.                 getline(cin, input);
  283.                 string choice = "";
  284.                 if(input == "стоп") {
  285.                     notCorrect = false;
  286.                     continueCycle = false;
  287.                 } else {
  288.                     try {
  289.                         int changeNum = stoi(input);
  290.                         if(changeNum <= data.size() && changeNum > 0) {
  291.                             Employee *emp = &data[changeNum-1];
  292.                             changedCount = changeEmployeeData(emp, 0);
  293.                             notCorrect = false;
  294.                         } else
  295.                             cout << "Сотрудник с таким номером не найден, повторите ввод." << endl;
  296.                     } catch (...) {
  297.                         cout << "Номер сотрудника должен быть числом, повторите ввод." << endl;
  298.                     }
  299.                 }
  300.             }
  301.             notCorrect = true;
  302.         }
  303.         if(changedCount > 0)
  304.             saveDataToFile(data, false);
  305.     }
  306.     showInfo();
  307.     executeAction(chooseAction());
  308. }
  309.  
  310. void deleteData() {
  311.     vector<Employee> data = grabData(true);
  312.     if(data.size() > 0) {
  313.         bool continueCycle = true;
  314.         bool notCorrect = true;
  315.         int deletedCount = 0;
  316.         while(continueCycle) {
  317.             cout << "Введите номер сотрудника, которого хотите удалить, либо [стоп], чтобы вернуться в меню" << endl;
  318.             while(notCorrect) {
  319.                 string input;
  320.                 getline(cin, input);
  321.                 if(input == "стоп") {
  322.                     notCorrect = false;
  323.                     continueCycle = false;
  324.                 } else {
  325.                     try {
  326.                         int deleteNum = stoi(input);
  327.                         if(deleteNum > 0 && deleteNum <= data.size()) {
  328.                             data.erase(data.begin()+deleteNum-1);
  329.                             deletedCount++;
  330.                             cout << "Сотрудник № " << deleteNum << " успешно удален." << endl;
  331.                             notCorrect = false;
  332.                         } else {
  333.                             cout << "Сотрудник с таким номером не найден, повторите ввод." << endl;
  334.                             notCorrect = true;
  335.                         }
  336.                     } catch (...) {
  337.                         cout << "Номер сотрудника должен быть числом." << endl;
  338.                         notCorrect = true;
  339.                     }
  340.                 }
  341.             }
  342.             notCorrect = true;
  343.         }
  344.         if(deletedCount > 0)
  345.             saveDataToFile(data, false);
  346.     }
  347.     showInfo();
  348.     executeAction(chooseAction());
  349. }
  350.  
  351. void showData() {
  352.     grabData(true);
  353.     showInfo();
  354.     executeAction(chooseAction());
  355. }
  356.  
  357. DepartmentData* grabCurrentDepartment(string departmentName, vector<DepartmentData> &departments) {
  358.     bool isInArr = false;
  359.     int i = 0;
  360.     DepartmentData *department = nullptr;
  361.     while(!isInArr && i < departments.size()) {
  362.         DepartmentData *temp = &departments[i];
  363.         if(temp->name == departmentName) {
  364.             isInArr = true;
  365.             department = temp;
  366.         }
  367.         i++;
  368.     }
  369.     return department;
  370. }
  371.  
  372. vector<DepartmentData> grabDepartments(vector<Employee> data) {
  373.     vector<DepartmentData> departments;
  374.     for(Employee emp : data) {
  375.         DepartmentData *department = grabCurrentDepartment(emp.department, departments);
  376.         if(department == nullptr)
  377.             departments.push_back(*new DepartmentData(emp.department, emp.salary));
  378.         else
  379.             department->sum += emp.salary;
  380.     }
  381.     return departments;
  382. }
  383.  
  384. void sortDepartments(vector<DepartmentData> &departments) {
  385.     for(int i = 0; i < departments.size(); i++) {
  386.         for(int j = 1; j < departments.size()-i; j++) {
  387.             DepartmentData *prev = &departments[j-1];
  388.             DepartmentData *curr = &departments[j];
  389.             char currName[curr->name.size()];
  390.             char prevName[prev->name.size()];
  391.             strcpy(currName, curr->name.c_str());
  392.             strcpy(prevName, prev->name.c_str());
  393.             if(strcmp(currName, prevName) < 0)
  394.                 swap(departments[j], departments[j-1]);
  395.         }
  396.     }
  397. }
  398.  
  399. void showDepartmentSum() {
  400.     vector<Employee> data = grabData(false);
  401.     vector<DepartmentData> departments = grabDepartments(data);
  402.     sortDepartments(departments);
  403.     for(DepartmentData department : departments) {
  404.         cout << department.name << endl;
  405.         cout << "Общая сумма выплат за месяц по отделу = " << department.sum << '\n' << endl;
  406.     }
  407.     showInfo();
  408.     executeAction(chooseAction());
  409. }
  410.  
  411. void executeAction(string action) {
  412.     if(action == "доб")
  413.         addData();
  414.     else if(action == "изм")
  415.         changeData();
  416.     else if(action == "уд")
  417.         deleteData();
  418.     else if(action == "выв")
  419.         showData();
  420.     else if(action == "сум")
  421.         showDepartmentSum();
  422.     else if(action == "выход")
  423.         exit(0);
  424. }
  425.  
  426. int main() {
  427.     setlocale(LC_ALL,".1251");
  428.     cout << "Данная программа позволяет работать со сведениями о месячной заработной плате сотрудников отдела.\n" << endl;
  429.     showInfo();
  430.     string action = chooseAction();
  431.     executeAction(action);
  432.     return 0;
  433. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement