-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSystem.h
More file actions
1346 lines (1187 loc) · 53.3 KB
/
Copy pathSystem.h
File metadata and controls
1346 lines (1187 loc) · 53.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define _CRT_SECURE_NO_WARNINGS
#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>
#include <map>
#include <unordered_map> // Подібна до map, але зберігає дані у неупорядкованому вигляді,
//що може забезпечувати швидкий доступ до даних.
#include <cstring> // Містить функції для роботи з рядками символів
#include "User.h"
#include "Admin.h"
#include "Test.h"
using namespace std;
const char n = '\n';
// Клас для системи
class System {
private:
vector<User> users; // вектор користувачів
vector<Test> tests; // вектор тестів
Admin admin; // дані адміністратора
bool isAdminSet = false; // прапорець для визначення, чи встановлений адмін
unordered_map<string, vector<string>> user_results; // результати користувачів
// Перевірка валідності пароля (наявність хоча б однієї великої літери та цифри)
bool validPassword(const string& password) {
bool hasUpper = false;
bool hasDigit = false;
for (char c : password) {
if (isupper(c)) hasUpper = true;
if (isdigit(c)) hasDigit = true;
if (hasUpper && hasDigit) return true;
}
return false;
}
// Шифрування методом Цезаря
string encryptCaesar(string text, int shift) {
string result = "";
for (char& c : text) {
if (isalpha(c)) {
char base = isupper(c) ? 'A' : 'a';
c = (c - base + shift) % 26 + base;
}
result += c;
}
return result;
}
// Пошук користувача за логіном
User* searchUser(const string& login) {
for (User& user : users) {
if (user.login == login) {
return &user;
}
}
return nullptr;
}
// Пошук тесту за назвою
Test* searchTest(const string& testName) {
for (Test& test : tests) {
if (test.name == testName) {
return &test;
}
}
return nullptr;
}
// Реєстрація нового користувача
void registerUser() {
User newUser;
do {
cout << "Name of user? ";
cin >> newUser.name;
// Перевірка, чи містить ім'я цифри
if (any_of(newUser.name.begin(), newUser.name.end(), ::isdigit)) {
cout << "The test taker's name cannot contain numbers! Please, try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "Enter the name of your village/town/city ";
cin >> newUser.location;
// Перевірка, чи містить назва локації цифри
if (any_of(newUser.location.begin(), newUser.location.end(), ::isdigit)) {
cout << "The location name must contain only letters! Try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "Enter the name of your street ";
cin >> newUser.street;
// Перевірка, чи містить назва вулиці цифри
if (any_of(newUser.street.begin(), newUser.street.end(), ::isdigit)) {
cout << "The street name must contain only letters! Try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "Enter the number of your house ";
cin >> newUser.house_number;
// Перевірка, чи містить номер будинку тільки цифри
if (none_of(newUser.house_number.begin(), newUser.house_number.end(), ::isdigit)) {
cout << "The house number must contain only numbers! Try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "Enter the number of your phone ";
cin >> newUser.num;
// Перевірка, чи містить номер телефону тільки цифри
if (none_of(newUser.num.begin(), newUser.num.end(), ::isdigit)) {
cout << "The phone number must contain only numbers! Try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "ENTER LOGIN ";
cin >> newUser.login;
// Перевірка, чи не зайнятий логін
if (searchUser(newUser.login)) {
cout << "This login is already taken. Please, try another one.\n";
continue;
}
cout << "ENTER PASSWORD ";
cin >> newUser.password;
// Перевірка валідності пароля
if (!validPassword(newUser.password)) {
cout << "Password must contain at least one digit and one uppercase letter. Try again!" << endl;
continue;
}
break;
} while (true);
// Шифрування логіну та пароля методом Цезаря
int shift = 3;
newUser.login = encryptCaesar(newUser.login, shift);
newUser.password = encryptCaesar(newUser.password, shift);
// Додавання нового користувача до списку користувачів
users.push_back(newUser);
cout << "Registration completed successfully!" << n;
saveUsersToFile(); // Зберігаємо користувача у файл
}
// Збереження списку користувачів у файл
void saveUsersToFile() {
ofstream userFile("users.txt");
if (userFile.is_open()) {
for (const auto& user : users) {
userFile << "Name: " << user.name << ", Location: " << user.location << ", Street: " << user.street << ", House Number: " << user.house_number << ", Phone Number: " << user.num << ", Login: " << user.login << ", Password: " << user.password << "\n";
}
userFile.close();
}
else {
cout << "Unable to open users file.";
}
}
// Збереження облікових даних адміністратора у файл
void saveAdminToFile() {
ofstream adminFile("admin.txt");
if (adminFile.is_open()) {
adminFile << "Name: " << admin.name << ", Location: " << admin.location << ", Street: " << admin.street << ", House Number: " << admin.house_number << ", Phone Number: " << admin.num << ", Login: " << admin.login << ", Password: " << admin.password << "\n";
adminFile.close();
}
else {
cout << "Unable to open admin file.";
}
}
// Завантаження облікових даних адміністратора з файлу
void loadAdminFromFile() {
ifstream adminFile("admin.txt");
if (adminFile.is_open()) {
string line;
getline(adminFile, line);
size_t pos;
pos = line.find("Name: ");
if (pos != string::npos) { //статична константа яка представляє максимально можливе значення для типу size_t
pos += 6;
size_t endPos = line.find(", Location: ", pos);
admin.name = line.substr(pos, endPos - pos);
}
pos = line.find("Location: ");
if (pos != string::npos) {
pos += 10;
size_t endPos = line.find(", Street: ", pos);
admin.location = line.substr(pos, endPos - pos);
}
pos = line.find("Street: ");
if (pos != string::npos) {
pos += 8;
size_t endPos = line.find(", House Number: ", pos);
admin.street = line.substr(pos, endPos - pos);
}
pos = line.find("House Number: ");
if (pos != string::npos) {
pos += 14;
size_t endPos = line.find(", Phone Number: ", pos);
admin.house_number = line.substr(pos, endPos - pos);
}
pos = line.find("Phone Number: ");
if (pos != string::npos) {
pos += 14;
size_t endPos = line.find(", Login: ", pos);
admin.num = line.substr(pos, endPos - pos);
}
pos = line.find("Login: ");
if (pos != string::npos) {
pos += 7;
size_t endPos = line.find(", Password: ", pos);
admin.login = line.substr(pos, endPos - pos);
}
pos = line.find("Password: ");
if (pos != string::npos) {
pos += 10;
admin.password = line.substr(pos);
}
isAdminSet = true;
adminFile.close();
}
else {
cout << "Unable to open admin file.";
}
}
// Завантаження списку користувачів з файлу
void loadUsersFromFile() {
ifstream userFile("users.txt");
if (userFile.is_open()) {
string line;
while (getline(userFile, line)) {
// Парсимо рядок і створюємо нового користувача
string name, location, street, house_number, num, login, password;
size_t pos;
pos = line.find("Name: ");
if (pos != string::npos) {
pos += 6;
size_t endPos = line.find(", Location: ", pos);
name = line.substr(pos, endPos - pos);
}
pos = line.find("Location: ");
if (pos != string::npos) {
pos += 10;
size_t endPos = line.find(", Street: ", pos);
location = line.substr(pos, endPos - pos);
}
pos = line.find("Street: ");
if (pos != string::npos) {
pos += 8;
size_t endPos = line.find(", House Number: ", pos);
street = line.substr(pos, endPos - pos);
}
pos = line.find("House Number: ");
if (pos != string::npos) {
pos += 14;
size_t endPos = line.find(", Phone Number: ", pos);
house_number = line.substr(pos, endPos - pos);
}
pos = line.find("Phone Number: ");
if (pos != string::npos) {
pos += 14;
size_t endPos = line.find(", Login: ", pos);
num = line.substr(pos, endPos - pos);
}
pos = line.find("Login: ");
if (pos != string::npos) {
pos += 7;
size_t endPos = line.find(", Password: ", pos);
login = line.substr(pos, endPos - pos);
}
pos = line.find("Password: ");
if (pos != string::npos) {
pos += 10;
password = line.substr(pos);
}
// Створюємо об'єкт користувача і додаємо його до вектора користувачів
User loadedUser(name, location, street, house_number, num, login, password);
users.push_back(loadedUser);
}
userFile.close();
}
else {
cout << "Unable to open file.";
}
}
// Завантаження списку тестів з файлу
void loadTestsFromFile() {
tests.clear(); // Очистка попередніх тестів перед завантаженням нових
ifstream inFile("saved_tests.txt");
if (inFile.is_open()) {
string line;
while (getline(inFile, line)) {
string category = line;
getline(inFile, line);
string testName = line;
Test test(category, testName);
size_t numQuestions;
inFile >> numQuestions;
inFile.ignore(); // Ігноруємо залишок рядка після числа
for (size_t i = 0; i < numQuestions; ++i) {
getline(inFile, line);
string questionText = line;
test.questions.push_back(questionText);
size_t numChoices;
inFile >> numChoices;
inFile.ignore(); // Ігноруємо залишок рядка після числа
vector<string> choices;
for (size_t j = 0; j < numChoices; ++j) {
getline(inFile, line);
choices.push_back(line);
}
test.answer_choices.push_back(choices);
size_t correctAnswerIndex;
inFile >> correctAnswerIndex;
inFile.ignore(); // Ігноруємо залишок рядка після числа
test.correct_answers_index.push_back(correctAnswerIndex);
}
tests.push_back(test);
}
inFile.close();
}
else {
cout << "Unable to open tests file." << endl;
}
}
// Збереження списку тестів у файл
void saveTestsToFile() {
ofstream outFile("saved_tests.txt");
if (outFile.is_open()) {
for (const auto& test : tests) {
outFile << test.category << endl;
outFile << test.name << endl;
outFile << test.questions.size() << endl;
for (size_t i = 0; i < test.questions.size(); ++i) {
outFile << test.questions[i] << endl;
outFile << test.answer_choices[i].size() << endl;
for (const auto& choice : test.answer_choices[i]) {
outFile << choice << endl;
}
outFile << test.correct_answers_index[i] << endl;
}
}
outFile.close();
}
else {
cout << "Unable to open output file." << endl;
}
}
public:
// Конструктор системи, завантажує дані при створенні
System() {
loadUsersFromFile(); // Завантажуємо користувачів з файлу при створенні системи
loadAdminFromFile();// Завантажуємо адміністратора з файлу
loadTestsFromFile(); //Завантажуємо тести
}
User* currentUser = nullptr; // Поточний користувач, що увійшов до системи
// Реєстрація адміністратора
void registerAdmin() {
if (isAdminSet) {
cout << "Admin already registered!" << n;
return;
}
Admin newAdmin;
// Введення даних адміністратора з перевіркою на валідність
do {
cout << "Enter the admin's name: ";
cin >> newAdmin.name;
if (any_of(newAdmin.name.begin(), newAdmin.name.end(), ::isdigit)) {
cout << "The admin's name cannot contain numbers! Please, try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "Enter the admin's location: ";
cin >> newAdmin.location;
if (any_of(newAdmin.location.begin(), newAdmin.location.end(), ::isdigit)) {
cout << "The location name must contain only letters! Try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "Enter the admin's street: ";
cin >> newAdmin.street;
if (any_of(newAdmin.street.begin(), newAdmin.street.end(), ::isdigit)) {
cout << "The street name must contain only letters! Try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "Enter the admin's house number: ";
cin >> newAdmin.house_number;
if (none_of(newAdmin.house_number.begin(), newAdmin.house_number.end(), ::isdigit)) {
cout << "The house number must contain only numbers! Try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "Enter the admin's phone number: ";
cin >> newAdmin.num;
if (none_of(newAdmin.num.begin(), newAdmin.num.end(), ::isdigit)) {
cout << "The phone number must contain only numbers! Try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "Enter the admin's login: ";
cin >> newAdmin.login;
if (!validPassword(newAdmin.login)) {
cout << "Login must contain at least one digit and one uppercase letter. Try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "Enter the admin's password: ";
cin >> newAdmin.password;
if (!validPassword(newAdmin.password)) {
cout << "Password must contain at least one digit and one uppercase letter. Try again!" << n;
continue;
}
break;
} while (true);
// Шифрування логіна та пароля методом Цезаря
int shift = 3;
newAdmin.login = encryptCaesar(newAdmin.login, shift);
newAdmin.password = encryptCaesar(newAdmin.password, shift);
admin = newAdmin; // Зберігаємо адміністратора у пам'яті
isAdminSet = true; // Встановлюємо прапорець, що адміністратор встановлений
cout << "Admin registration completed successfully!" << n;
saveAdminToFile(); // Зберігаємо адміністратора у файл
}
// Вхід користувача в систему
void userLogin() {
string enteredLogin, enteredPassword;
cout << "Enter login: ";
cin >> enteredLogin;
cout << "Enter password: ";
cin >> enteredPassword;
// Шифрування введеного логіна та пароля методом Цезаря
int shift = 3;
enteredLogin = encryptCaesar(enteredLogin, shift);
enteredPassword = encryptCaesar(enteredPassword, shift);
// Пошук користувача за введеним логіном
User* user = searchUser(enteredLogin);
// Перевірка введених даних з даними користувача
if (enteredLogin == user->login && enteredPassword == user->password) {
cout << "Login successful! Welcome, " << user->name << "!\n";
currentUser = user; // Встановлюємо поточного користувача
userMenu(); // Показуємо меню користувача
}
else {
cout << "Login failed! Invalid login or password.\n";
}
}
// Меню користувача після входу в систему
void userMenu() {
int choice;
do {
cout << n << "User Menu:" << n;
cout << "1. Take a test" << n;
cout << "2. View previous results" << n;
cout << "3. Logout" << n;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
takeTest(); // Розпочати проходження тесту
break;
case 2:
viewUserResults(); // Перегляд попередніх результатів користувача
break;
case 3:
cout << "Logging out." << n;
currentUser = nullptr; // Закінчення сеансу користувача
return;
default:
cout << "Invalid choice. Please enter again." << n;
break;
}
} while (true);
}
// Пошук тесту за назвою у файлі
Test* searchTestFromFile(const string& testName) {
ifstream inFile("saved_tests.txt");
if (!inFile.is_open()) {
cout << "Unable to open 'saved_tests.txt' for reading.\n";
return nullptr;
}
string line;
Test* foundTest = nullptr;
while (getline(inFile, line)) {
if (line.find("Test Name: " + testName) != string::npos) {
foundTest = new Test();
foundTest->name = testName;
getline(inFile, line);
while (getline(inFile, line) && line != "") {
if (line.substr(0, 9) == "Question ") {
foundTest->questions.push_back(line);
getline(inFile, line);
vector<string> choices;
for (int i = 0; i < 4; ++i) {
getline(inFile, line);
choices.push_back(line.substr(3));
}
foundTest->answer_choices.push_back(choices);
getline(inFile, line);
int correctIndex = stoi(line.substr(14));
foundTest->correct_answers_index.push_back(correctIndex);
}
}
break;
}
}
inFile.close();
return foundTest;
}
// Проходження тесту користувачем
void takeTest() {
if (!currentUser) {
cout << "No user logged in." << n;
return;
}
if (tests.empty()) {
cout << "No categories available." << n;
return;
}
// Вибір категорії тестів
vector<string> categories;
for (const auto& test : tests) {
bool found = false;
for (const auto& category : categories) {
if (category == test.category) {
found = true;
break;
}
}
if (!found) {
categories.push_back(test.category);
}
}
cout << "Choose a category:" << n;
for (size_t i = 0; i < categories.size(); ++i) {
cout << i + 1 << ". " << categories[i] << n;
}
int categoryChoice;
cout << "Enter your choice: ";
cin >> categoryChoice;
string chosenCategory = categories[categoryChoice - 1];
// Вибір конкретного тесту у вибраній категорії
vector<Test> testsInCategory;
for (const auto& test : tests) {
if (test.category == chosenCategory) {
testsInCategory.push_back(test);
}
}
cout << "Choose a test:" << n;
for (size_t i = 0; i < testsInCategory.size(); ++i) {
cout << i + 1 << ". " << testsInCategory[i].name << n;
}
int testChoice;
cout << "Enter your choice: ";
cin >> testChoice;
Test* chosenTest = &testsInCategory[testChoice - 1];
int correctCount = 0;
// Проходження кожного питання тесту
for (size_t i = 0; i < chosenTest->questions.size(); ++i) {
cout << "Question " << i + 1 << ": " << chosenTest->questions[i] << "\n";
for (size_t j = 0; j < chosenTest->answer_choices[i].size(); ++j) {
cout << " " << j + 1 << ". " << chosenTest->answer_choices[i][j] << "\n";
}
int answer;
cout << "Enter your answer (1-4): ";
cin >> answer;
if (answer - 1 == chosenTest->correct_answers_index[i]) {
++correctCount;
}
}
// Обчислення результатів тесту
double percentageCorrect = (static_cast<double>(correctCount) / chosenTest->questions.size()) * 100;
int score = static_cast<int>(percentageCorrect / 100 * 12);
// Формування результатів тесту для виведення користувачу
string result = "Test: " + chosenTest->name + "\n";
result += "Number of correct answers: " + to_string(correctCount) + "\n";
result += "Percentage of correct answers: " + to_string(percentageCorrect) + "%\n";
result += "Score (out of 12): " + to_string(score) + "\n";
cout << "Test completed.\n";
cout << result << "\n";
// Збереження результатів користувача
user_results[currentUser->login].push_back(result);
saveStatisticsToFile(user_results);
}
// Збереження статистики у файл
void saveStatisticsToFile(const unordered_map<string, vector<string>>& user_results) {
ofstream outFile("statistics.txt", ios::app); // Відкриття файлу у режимі додавання
if (outFile.is_open()) {
for (const auto& entry : user_results) {
outFile << "User: " << entry.first << "\n";
for (const string& result : entry.second) {
outFile << result << "\n";
}
outFile << "\n"; // Роздільник між користувачами
}
outFile.close();
cout << "Statistics saved successfully.\n";
}
else {
cout << "Unable to open statistics file.\n";
}
}
// Завантаження статистики з файлу
void loadStatisticsFromFile() {
ifstream inFile("statistics.txt");
if (inFile.is_open()) {
string line, user;
while (getline(inFile, line)) {
if (line.find("User: ") == 0) {
user = line.substr(6);
user_results[user] = vector<string>();
}
else if (!line.empty()) {
user_results[user].push_back(line);
}
}
inFile.close();
}
else {
cout << "Unable to open statistics file.\n";
}
}
// Перегляд результатів користувача
void viewUserResults() {
if (!currentUser) {
cout << "No user logged in." << "\n";
return;
}
loadStatisticsFromFile(); // Завантаження статистики перед відображенням
cout << "Results for user: " << currentUser->name << "\n";
const auto& results = user_results[currentUser->login];
for (const auto& result : results) {
cout << " - " << result << "\n";
}
}
// Перегляд результатів всіх користувачів
void viewResultsOfAllUsers(const unordered_map<string, vector<string>>& user_results) {
ifstream inFile("statistics.txt");
if (inFile.is_open()) {
string line;
while (getline(inFile, line)) {
// Зчитуємо ім'я користувача
if (line.find("User: ") != string::npos) {
string username = line.substr(6); // Отримуємо ім'я користувача
cout << "User: " << username << "\n";
// Виводимо результати тестів користувача
while (getline(inFile, line) && !line.empty()) {
cout << line << "\n";
}
cout << "\n"; // Роздільник між користувачами
}
}
inFile.close();
}
else {
cout << "Unable to open statistics file.\n";
}
}
// Функція для входу адміністратора
void adminLogin() {
if (!isAdminSet) {
cout << "Admin is not registered yet. Please register admin first." << n;
return;
}
string login, password;
cout << "Enter admin login: ";
cin >> login;
cout << "Enter admin password: ";
cin >> password;
int shift = 3;
login = encryptCaesar(login, shift);
password = encryptCaesar(password, shift);
if (login == admin.login && password == admin.password) {
cout << "Admin login successful!" << n;
adminMenu(); // Перехід до меню адміністратора
}
else {
cout << "Invalid admin credentials. Please try again." << n;
}
}
// Функція для редагування тесту
void editTest() {
string testName;
cout << "Enter the name of the test you want to edit: ";
cin >> testName;
Test* testToEdit = searchTest(testName);
if (testToEdit == nullptr) {
cout << "Test with name '" << testName << "' not found." << n;
return;
}
int choice;
do {
cout << n << "Edit Test - " << testToEdit->name << ":" << n;
cout << "1. Add a question" << n;
cout << "2. Remove a question" << n;
cout << "3. Exit" << n;
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1: {
string question;
cout << "Enter the question you want to add: ";
cin.ignore();
getline(cin, question);
vector<string> choices;
for (int j = 0; j < 4; ++j) {
string choice;
cout << "Enter choice " << j + 1 << ": ";
getline(cin, choice);
choices.push_back(choice);
}
int correctIndex;
cout << "Enter index of correct choice (1-4): ";
cin >> correctIndex;
testToEdit->addQuestion(question, choices, correctIndex - 1);
cout << "Question added successfully!" << n;
break;
}
case 2: {
int index;
cout << "Enter the index of the question you want to remove (1-" << testToEdit->questions.size() << "): ";
cin >> index;
if (index < 1 || index > testToEdit->questions.size()) {
cout << "Invalid index. Please try again." << n;
break;
}
testToEdit->questions.erase(testToEdit->questions.begin() + index - 1);
testToEdit->answer_choices.erase(testToEdit->answer_choices.begin() + index - 1);
testToEdit->correct_answers_index.erase(testToEdit->correct_answers_index.begin() + index - 1);
cout << "Question removed successfully!" << n;
break;
}
case 3:
cout << "Exiting edit menu." << n;
return;
default:
cout << "Invalid choice. Please enter again." << n;
break;
}
} while (true);
saveTestsToFile(); //Збереження у файл
}
// Функція для додавання користувача адміністратором
void addUserByAdmin() {
if (!isAdminSet) {
cout << "Admin is not registered yet. Please register admin first." << n;
return;
}
User newUser;
do {
cout << "Enter the name of the user: ";
cin >> newUser.name;
if (any_of(newUser.name.begin(), newUser.name.end(), ::isdigit)) {
cout << "The user's name cannot contain numbers! Please, try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "Enter the location of the user: ";
cin >> newUser.location;
if (any_of(newUser.location.begin(), newUser.location.end(), ::isdigit)) {
cout << "The location name must contain only letters! Try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "Enter the street of the user: ";
cin >> newUser.street;
if (any_of(newUser.street.begin(), newUser.street.end(), ::isdigit)) {
cout << "The street name must contain only letters! Try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "Enter the house number of the user: ";
cin >> newUser.house_number;
if (none_of(newUser.house_number.begin(), newUser.house_number.end(), ::isdigit)) {
cout << "The house number must contain only numbers! Try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "Enter the phone number of the user: ";
cin >> newUser.num;
if (none_of(newUser.num.begin(), newUser.num.end(), ::isdigit)) {
cout << "The phone number must contain only numbers! Try again!" << n;
continue;
}
break;
} while (true);
do {
cout << "Enter the login of the user: ";
cin >> newUser.login;
if (searchUser(newUser.login)) {
cout << "This login is already taken. Please, try another one.\n";
continue;
}
cout << "Enter the password of the user: ";
cin >> newUser.password;
if (!validPassword(newUser.password)) {
cout << "Password must contain at least one digit and one uppercase letter. Try again!" << endl;
continue;
}
break;
} while (true);
int shift = 3;
newUser.login = encryptCaesar(newUser.login, shift);
newUser.password = encryptCaesar(newUser.password, shift);
users.push_back(newUser);
cout << "User added successfully!" << n;
saveUsersToFile(); // Зберігаємо користувача у файл
}
// Функція для видалення користувача адміністратором
void deleteUserByAdmin() {
if (!isAdminSet) {
cout << "Admin is not registered yet. Please register admin first." << n;
return;
}
string login;
cout << "Enter the login of the user you want to delete: ";
cin >> login;
// Видалення користувача з вектора за логіном
auto it = std::remove_if(users.begin(), users.end(), [&](const User& user) { return user.login == login; });
if (it != users.end()) {
users.erase(it, users.end());
cout << "User with login '" << login << "' deleted successfully." << n;
saveUsersToFile(); // Зберігаємо оновлений список користувачів у файл
}
else {
cout << "User with login '" << login << "' not found." << n;
}
}
// Функція для модифікації користувача адміністратором
void modifyUserByAdmin() {
if (!isAdminSet) {
cout << "Admin is not registered yet. Please register admin first." << n;
return;
}
string login;
cout << "Enter the login of the user you want to modify: ";
cin >> login;
// Пошук користувача за логіном
User* userToModify = searchUser(login);
if (userToModify) {
cout << "User found. Enter new details:" << n;
// Введення нових даних про користувача
cout << "Enter the name of the user: ";
cin >> userToModify->name;
cout << "Enter the location of the user: ";
cin >> userToModify->location;
cout << "Enter the street of the user: ";
cin >> userToModify->street;
cout << "Enter the house number of the user: ";
cin >> userToModify->house_number;
cout << "Enter the phone number of the user: ";
cin >> userToModify->num;
cout << "Enter the login of the user: ";
cin >> userToModify->login;
cout << "Enter the password of the user: ";
cin >> userToModify->password;
// Шифрування логіну та паролю користувача
int shift = 3;
userToModify->login = encryptCaesar(userToModify->login, shift);
userToModify->password = encryptCaesar(userToModify->password, shift);