Advertisement
niks32

NikitaLearn2

Oct 26th, 2022
889
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 9.55 KB | None | 0 0
  1. #include<iostream>
  2. #include<map>
  3. #include<vector>
  4. #include<iterator>
  5. #include<fstream>
  6. #include<Windows.h> // Обязательно для SetConsoleCP() и SetConsoleOutputCP()
  7.  
  8. using namespace std;
  9.  
  10. struct Student
  11. {
  12.     char name[30];
  13.     int group;
  14.     int score[5];
  15. };
  16.  
  17. void printDataStudent(const vector<Student>& currentStudents);
  18.  
  19. void chekMidScore(const vector<Student>& currentStudents, vector<Student>& filterResult);
  20. void chekScoreToTwo(const vector<Student>& currentStudents, vector<Student>& filterResult);
  21. void chekScoreToForFive(const vector<Student>& currentStudents, vector<Student>& filterResult);
  22.  
  23. int getCountOfStudents(const char fileName[]);
  24. void addStudent(FILE* f, int& countOfStudent);
  25. void removeStudent(FILE* f, int& countOfStudent, const char fileName[]);
  26.  
  27. //Объяви тип указатель на функцию, которая принимает на вход массив структур студентов (и
  28. typedef void(*studentFilter)(const vector<Student>&, vector<Student>&);
  29.  
  30. typedef map<int, studentFilter> studentFilterMap;
  31. typedef map<int, studentFilter>::const_iterator menuFilterIter;
  32.  
  33. void convertFileToVector(FILE* f, int &countOfStudent, vector<Student> &currentStudents)
  34. {
  35.     Student tmpStudent;
  36.     for (int i = 0; i < countOfStudent; i++)
  37.     {
  38.         fseek(f, i * sizeof(Student), SEEK_SET); // перемещаемся от начала (SEEK_SET) файла f на i длинны пакета
  39.         fread(&tmpStudent, sizeof(Student), 1, f); // считываем из файла f ровно 1 пакет pack размера int_double
  40.         currentStudents.push_back(tmpStudent);
  41.     }
  42. }
  43.  
  44. int main()
  45. {
  46.     SetConsoleCP(1251);
  47.     SetConsoleOutputCP(1251);
  48.    
  49.     bool menuFlag = true;
  50.  
  51.     vector<Student> currentStudents;
  52.     vector<Student> filterResult;
  53.     int key;
  54.     char fileName[] = "students.dat";
  55.     int countOfStudent = getCountOfStudents(fileName);
  56.     FILE *f; // переменная для работы с файлом
  57.     fopen_s(&f, fileName, "ab+");
  58.  
  59.     //Объяви map, ключ это номер выбора из меню, значение это указатель на функцию
  60.     const studentFilterMap MENU =
  61.     {
  62.         {1, chekMidScore},
  63.         {2, chekScoreToTwo},
  64.         {3, chekScoreToForFive}
  65.     };
  66.     menuFilterIter it_MENU;
  67.  
  68.     while (menuFlag)
  69.     {
  70.         cout << endl;
  71.         cout << "Выберите действие:" << endl;
  72.         cout << "1) Вывести список студентов на экран" << endl;
  73.         cout << "2) Добавить студента" << endl;
  74.         cout << "3) Удалить студента" << endl;
  75.         cout << "Введите номер действия ";
  76.         cin >> key;
  77.         cin.get(); // считывает из потока Enter который пользователь нажимает после последнего ввода
  78.            
  79.         switch (key) {
  80.         case 1:
  81.             convertFileToVector(f, countOfStudent, currentStudents);
  82.  
  83.             cout << endl;
  84.             cout << "1) Средний балл студента больше 4.0" << endl;
  85.             cout << "2) Имеющих хотя бы одну оценку 2" << endl;
  86.             cout << "3) Имеющих оценки 4 и 5" << endl;
  87.             cout << " > ";
  88.             cin >> key;
  89.  
  90.             it_MENU = MENU.find(key);
  91.             if (it_MENU == MENU.end())
  92.             {
  93.                 cout << "Такой инструкции нет!!!" << endl;
  94.             }
  95.             else
  96.             {
  97.                 it_MENU->second(currentStudents, filterResult);
  98.                 printDataStudent(filterResult);
  99.             }
  100.             break;
  101.         case 2:
  102.             addStudent(f, countOfStudent);
  103.             break;
  104.         case 3:
  105.             removeStudent(f, countOfStudent, fileName);
  106.             break;
  107.         default:
  108.             cout << "Введенный номер не корректен" << endl;
  109.             break;
  110.         }
  111.     }
  112.  
  113.     fclose(f); //Закрываем файл
  114.     return 0;
  115. }
  116.  
  117. void printDataStudent(const vector<Student>& currentStudents)
  118. {
  119.     for (int i = 0; i < currentStudents.size(); i++)
  120.     {
  121.         cout << "------------------------------------------------" << endl;
  122.         cout << "Имя, фамилие студента: " << currentStudents[i].name << endl;
  123.         cout << "Номер группы: " << currentStudents[i].group << endl;
  124.         for (int j = 0; j < 5; j++)
  125.         {
  126.             cout << currentStudents[i].score[j] << "   ";
  127.         }
  128.         cout << endl;
  129.     }
  130.  
  131.     if (currentStudents.empty())
  132.     {
  133.         cout << "Студентов удовлетваряющих условиям нет!" << endl;
  134.     }
  135. }
  136.  
  137. void chekMidScore(const vector<Student> & currentStudents, vector<Student> & filterResult)
  138. {
  139.     filterResult.clear();
  140.  
  141.     double tmpMidlScore; // средний балл текущего студента
  142.     for (int i = 0; i < currentStudents.size(); i++)
  143.     {
  144.         tmpMidlScore = 0;
  145.         for (int j = 0; j < 5; j++)
  146.         {
  147.             tmpMidlScore = tmpMidlScore + currentStudents[i].score[j];
  148.         }
  149.         tmpMidlScore = tmpMidlScore / 5;
  150.  
  151.         if (tmpMidlScore > 4.0)
  152.         {
  153.             filterResult.push_back(currentStudents[i]);
  154.         }
  155.     }
  156. }
  157.  
  158. void chekScoreToTwo(const vector<Student> & currentStudents, vector<Student> & filterResult)
  159. {
  160.     filterResult.clear();
  161.  
  162.     for (int i = 0; i < currentStudents.size(); i++)
  163.     {
  164.         for (int j = 0; j < 5; j++)
  165.         {
  166.             if (currentStudents[i].score[j] == 2)
  167.             {
  168.                 filterResult.push_back(currentStudents[i]);
  169.                 break;
  170.             }
  171.         }
  172.     }
  173. }
  174.  
  175. void chekScoreToForFive(const vector<Student> & currentStudents, vector<Student> & filterResult)
  176. {
  177.     filterResult.clear();
  178.  
  179.     for (int i = 0; i < currentStudents.size(); i++)
  180.     {
  181.         //есть еще идея как реализовать проверку. Сперва добавлять все обьекты, после (если находим другие оценки, удалять)
  182.         for (int j = 0; j < 5; j++)
  183.         {
  184.             if (currentStudents[i].score[j] == 4 || currentStudents[i].score[j] == 5)
  185.             {
  186.                 if (j = 5)
  187.                 {
  188.                     filterResult.push_back(currentStudents[i]);
  189.                 }
  190.             }
  191.             else
  192.             {
  193.                 break;
  194.             }
  195.         }
  196.     }
  197. }
  198.  
  199. int getCountOfStudents(const char fileName[]) //Узнаем размер файла
  200. {
  201.     fstream fp;
  202.     fp.open(fileName, ios::binary | ios::in);
  203.     if (!fp)
  204.     {
  205.         printf("%s", "Error opening file");
  206.         system("pause");
  207.         return -1; //ошибка, файл не существует или еще че-то;
  208.     }
  209.     fp.seekg(0, ios::end); //указатель на конец файла
  210.     unsigned long fSize;
  211.     fSize = fp.tellg();  //получили размер файла в fSize
  212.     fp.close();    //закрыли файл
  213.     return fSize / sizeof(Student);
  214. }
  215.  
  216. void addStudent(FILE* f, int& countOfStudent)
  217. {
  218.     Student curStudent;
  219.  
  220.     cout << "----Ввод данных о студенте------------------------------------------" << endl;
  221.     cout << "Введите Имя, Фамилие студента: ";
  222.     cin.getline(curStudent.name, 30);
  223.     cout << "Введите номер группы: ";
  224.     cin >> curStudent.group;
  225.  
  226.     for (int j = 0; j < 5; j++)
  227.     {
  228.         cout << "Введите оценку №" << j + 1 << " ";
  229.         cin >> curStudent.score[j];
  230.     }
  231.     cin.get(); // считывает из потока Enter который пользователь нажимает после последнего ввода
  232.  
  233.     if (f != 0)
  234.     {
  235.         countOfStudent = countOfStudent + 1;
  236.         fwrite(&curStudent, sizeof(curStudent), 1, f); // записываем в файл f ровно 1 пакет
  237.     }
  238. }
  239.  
  240. void removeStudent(FILE* f, int& countOfStudent, const char fileName[])
  241. {
  242.     Student tmpStudent;
  243.     vector<Student> Students;
  244.     int tmpKey = 0;
  245.  
  246.     cout << "Список студентов: " << endl;
  247.     for (int i = 0; i < countOfStudent; i++)
  248.     {
  249.         fseek(f, i * sizeof(Student), SEEK_SET); // перемещаемся от начала (SEEK_SET) файла f на i длинны пакета
  250.         fread(&tmpStudent, sizeof(Student), 1, f); // считываем из файла f ровно 1 пакет pack размера int_double
  251.         cout << i + 1 << ") " << tmpStudent.name << endl;
  252.         Students.push_back(tmpStudent);
  253.     }
  254.     cout << "Введите номер студента, которого необходимо удалить - ";
  255.     cin >> tmpKey;
  256.  
  257.     fclose(f); //Закрываем файл
  258.     fopen_s(&f, fileName, "w");
  259.  
  260.     for (int i = 0; i < countOfStudent; i++)
  261.     {
  262.         if (i == tmpKey - 1)
  263.         {
  264.             continue;
  265.         }
  266.         fwrite(&Students[i], sizeof(tmpStudent), 1, f); // записываем в файл f ровно 1 пакет
  267.     }
  268.     countOfStudent = countOfStudent - 1;
  269. }
  270.  
  271. // Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки"
  272. // Отладка программы: F5 или меню "Отладка" > "Запустить отладку"
  273.  
  274. // Советы по началу работы
  275. //   1. В окне обозревателя решений можно добавлять файлы и управлять ими.
  276. //   2. В окне Team Explorer можно подключиться к системе управления версиями.
  277. //   3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения.
  278. //   4. В окне "Список ошибок" можно просматривать ошибки.
  279. //   5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода.
  280. //   6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
  281.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement