Advertisement
Alyks

Untitled

Mar 22nd, 2020
321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 16.04 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(strcmp(surname, "стоп") == 0) {
  157.                 continueCycle = false;
  158.                 notCorrect = false;
  159.             } else {
  160.                 cout << "Введите название отдела" << endl;
  161.                 cin.getline(department, 20);
  162.                 cout << "Введите заработную плату сотрудника" << endl;
  163.                 string str;
  164.                 getline(cin, str);
  165.                 try {
  166.                     salary = stod(str);
  167.                     if(salary > -1)
  168.                         notCorrect = false;
  169.                     else {
  170.                         notCorrect = true;
  171.                         cout << "Заработная плата не может быть отрицательной, повторите ввод" << endl;
  172.                     }
  173.                 } catch(...) {
  174.                     notCorrect = true;
  175.                     cout << "Возникла ошибка при вводе данных, повторите ввод." << endl;
  176.                 }
  177.             }
  178.         }
  179.         if(strcmp(surname, "стоп") != 0) {
  180.             notCorrect = true;
  181.             data.push_back(*new Employee(surname, department, salary));
  182.         }
  183.     }
  184.     saveDataToFile(data, true);
  185.     showInfo();
  186.     executeAction(chooseAction());
  187. }
  188.  
  189. string makeChoice(vector<string> choices) {
  190.     string choice = "";
  191.     while(find(choices.begin(), choices.end(), choice) == choices.end()) {
  192.         cout << "Введите либо [д], либо [н]" << endl;
  193.         getline(cin, choice);
  194.     }
  195.     return choice;
  196. }
  197.  
  198. int changeEmployeeData(Employee *emp, int changes) {
  199.     cin.clear();
  200.     string choice = "";
  201.     vector<string> choices = {"д", "н"};
  202.     cout << "Хотите изменить фамилию?" << endl;
  203.     choice = makeChoice(choices);
  204.     if(choice == "д") {
  205.         cout << "Введите новую фамилию" << endl;
  206.         char surname[20];
  207.         cin.getline(surname, 20);
  208.         strcpy(emp->surname, surname);
  209.         cout << "Фамилия успешно изменена, хотите продолжить изменение данных?" << endl;
  210.         changes++;
  211.         choice = makeChoice(choices);
  212.         if(choice == "д")
  213.             changeEmployeeData(emp, changes);
  214.     } else {
  215.         cout << "Хотите изменить наименование отдела?" << endl;
  216.         choice = makeChoice(choices);
  217.         if(choice == "д") {
  218.             cout << "Введите наименование отдела" << endl;
  219.             char department[20];
  220.             cin.getline(department, 20);
  221.             strcpy(emp->department, department);
  222.             cout << "Наименование отдела успешно изменено, хотите продолжить изменение данных?" << endl;
  223.             changes++;
  224.             choice = makeChoice(choices);
  225.             if(choice == "д")
  226.                 changeEmployeeData(emp, changes);
  227.         } else {
  228.             cout << "Хотите изменить размер заработной платы?" << endl;
  229.             choice = makeChoice(choices);
  230.             if(choice == "д") {
  231.                 bool notCorrect = true;
  232.                 cout << "Введите размер заработной платы" << endl;
  233.                 while(notCorrect) {
  234.                     double salary;
  235.                     string str;
  236.                     try {
  237.                         getline(cin, str);
  238.                         salary = stod(str);
  239.                         if(salary > -1) {
  240.                             notCorrect = false;
  241.                             emp->salary = salary;
  242.                             cout << "Заработная плата успешно изменена" << endl;
  243.                             changes++;
  244.                         } else {
  245.                             notCorrect = true;
  246.                             cout << "Заработная плата не может быть отрицательной, повторите ввод" << endl;
  247.                         }
  248.                     } catch (...) {
  249.                         cout << "Заработная плата должна быть числом" << endl;
  250.                     }
  251.                 }
  252.             }
  253.         }
  254.     }
  255.     return changes;
  256. }
  257.  
  258. void changeData() {
  259.     vector<Employee> data = grabData(true);
  260.     if(data.size() > 0) {
  261.         bool continueCycle = true;
  262.         bool notCorrect = true;
  263.         int changedCount = 0;
  264.         while(continueCycle) {
  265.             cout << "Введите номер сотрудника, данные которого хотите изменить, либо [стоп], чтобы вернуться в меню" << endl;
  266.             while(notCorrect) {
  267.                 string input;
  268.                 getline(cin, input);
  269.                 string choice = "";
  270.                 if(input == "стоп") {
  271.                     notCorrect = false;
  272.                     continueCycle = false;
  273.                 } else {
  274.                     try {
  275.                         int changeNum = stoi(input);
  276.                         if(changeNum <= data.size() && changeNum > 0) {
  277.                             Employee *emp = &data[changeNum-1];
  278.                             changedCount = changeEmployeeData(emp, 0);
  279.                             notCorrect = false;
  280.                         } else
  281.                             cout << "Сотрудник с таким номером не найден, повторите ввод." << endl;
  282.                     } catch (...) {
  283.                         cout << "Номер сотрудника должен быть числом, повторите ввод." << endl;
  284.                     }
  285.                 }
  286.             }
  287.             notCorrect = true;
  288.         }
  289.         if(changedCount > 0)
  290.             saveDataToFile(data, false);
  291.     }
  292.     showInfo();
  293.     executeAction(chooseAction());
  294. }
  295.  
  296. void deleteData() {
  297.     vector<Employee> data = grabData(true);
  298.     if(data.size() > 0) {
  299.         bool continueCycle = true;
  300.         bool notCorrect = true;
  301.         int deletedCount = 0;
  302.         while(continueCycle) {
  303.             cout << "Введите номер сотрудника, которого хотите удалить, либо [стоп], чтобы вернуться в меню" << endl;
  304.             while(notCorrect) {
  305.                 string input;
  306.                 getline(cin, input);
  307.                 if(input == "стоп") {
  308.                     notCorrect = false;
  309.                     continueCycle = false;
  310.                 } else {
  311.                     try {
  312.                         int deleteNum = stoi(input);
  313.                         if(deleteNum > 0 && deleteNum <= data.size()) {
  314.                             data.erase(data.begin()+deleteNum-1);
  315.                             deletedCount++;
  316.                             cout << "Сотрудник № " << deleteNum << " успешно удален." << endl;
  317.                             notCorrect = false;
  318.                         } else {
  319.                             cout << "Сотрудник с таким номером не найден, повторите ввод." << endl;
  320.                             notCorrect = true;
  321.                         }
  322.                     } catch (...) {
  323.                         cout << "Номер сотрудника должен быть числом." << endl;
  324.                         notCorrect = true;
  325.                     }
  326.                 }
  327.             }
  328.             notCorrect = true;
  329.         }
  330.         if(deletedCount > 0)
  331.             saveDataToFile(data, false);
  332.     }
  333.     showInfo();
  334.     executeAction(chooseAction());
  335. }
  336.  
  337. void showData() {
  338.     grabData(true);
  339.     showInfo();
  340.     executeAction(chooseAction());
  341. }
  342.  
  343. DepartmentData* grabCurrentDepartment(string departmentName, vector<DepartmentData> &departments) {
  344.     bool isInArr = false;
  345.     int i = 0;
  346.     DepartmentData *department = nullptr;
  347.     while(!isInArr && i < departments.size()) {
  348.         DepartmentData *temp = &departments[i];
  349.         if(temp->name == departmentName) {
  350.             isInArr = true;
  351.             department = temp;
  352.         }
  353.         i++;
  354.     }
  355.     return department;
  356. }
  357.  
  358. vector<DepartmentData> grabDepartments(vector<Employee> data) {
  359.     vector<DepartmentData> departments;
  360.     for(Employee emp : data) {
  361.         DepartmentData *department = grabCurrentDepartment(emp.department, departments);
  362.         if(department == nullptr)
  363.             departments.push_back(*new DepartmentData(emp.department, emp.salary));
  364.         else
  365.             department->sum += emp.salary;
  366.     }
  367.     return departments;
  368. }
  369.  
  370. void sortDepartments(vector<DepartmentData> &departments) {
  371.     for(int i = 0; i < departments.size(); i++) {
  372.         for(int j = 1; j < departments.size()-i; j++) {
  373.             DepartmentData *prev = &departments[j-1];
  374.             DepartmentData *curr = &departments[j];
  375.             char currName[curr->name.size()];
  376.             char prevName[prev->name.size()];
  377.             strcpy(currName, curr->name.c_str());
  378.             strcpy(prevName, prev->name.c_str());
  379.             if(strcmp(currName, prevName) < 0)
  380.                 swap(departments[j], departments[j-1]);
  381.         }
  382.     }
  383. }
  384.  
  385. void showDepartmentSum() {
  386.     vector<Employee> data = grabData(false);
  387.     vector<DepartmentData> departments = grabDepartments(data);
  388.     sortDepartments(departments);
  389.     for(DepartmentData department : departments) {
  390.         cout << department.name << endl;
  391.         cout << "Общая сумма выплат за месяц по отделу = " << department.sum << '\n' << endl;
  392.     }
  393.     showInfo();
  394.     executeAction(chooseAction());
  395. }
  396.  
  397. void executeAction(string action) {
  398.     if(action == "доб")
  399.         addData();
  400.     else if(action == "изм")
  401.         changeData();
  402.     else if(action == "уд")
  403.         deleteData();
  404.     else if(action == "выв")
  405.         showData();
  406.     else if(action == "сум")
  407.         showDepartmentSum();
  408.     else if(action == "выход")
  409.         exit(0);
  410. }
  411.  
  412. int main() {
  413.     setlocale(LC_ALL,".1251");
  414.     cout << "Данная программа позволяет работать со сведениями о месячной заработной плате сотрудников отдела.\n" << endl;
  415.     showInfo();
  416.     string action = chooseAction();
  417.     executeAction(action);
  418.     return 0;
  419. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement