This repository has been archived by the owner on Jun 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GPA.cpp
605 lines (546 loc) · 23.9 KB
/
GPA.cpp
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
#include <iostream>
#include <string>
#include <stdlib.h>
#include <map>
#include <vector>
#include <cmath>
#include <fstream>
#include <sys/stat.h>
#include <chrono>
#include <iomanip>
#include <thread>
#include <limits>
#include "../dep/jsoncpp/jsoncpp.cpp" // relies on jsoncpp at https://github.com/open-source-parsers/jsoncpp
typedef std::map<std::string, std::tuple<std::string, int>> gpaHashMapStruc;
const std::string version = "0.2.0";
Json::Reader reader;
Json::Value root;
const std::string jsonFile = "gpa.json";
const std::string errorLogFile = "error-log-v" + version + ".log";
// based on https://www.nyp.edu.sg/current-students/academic-matters/nyp-assessment-regulations.html
const std::map<std::string, float> gpaRef = {
{"DIST", 4.0}, // awarded by the Assessment Board, though it is the same as grade A
{"A", 4.0},
{"B+", 3.5},
{"B", 3.0},
{"C+", 2.5},
{"C", 2.0},
{"D+", 1.5},
{"D", 1.0},
{"F", 0.0},
{"P", 0.0} // p for pass (GSM), will not be used during calculation of GPA
};
bool checkIfUppercase(std::string& input)
{
for (auto &c : input) {
if (!isupper(c)) return false;
}
return true;
}
void uppercaseInput(std::string& s)
{
int i = 0;
for (auto &c : s) {
s[i] = toupper(c);
i++;
}
}
void titleInput(std::string& s)
{
int toUpper = 1; int i = 0;
for (auto &c : s) {
if (toUpper) {
s[i] = toupper(c);
toUpper = 0;
} else if(isspace(s[i])) {
toUpper = 1;
} else {
s[i] = tolower(c);
}
i++;
}
}
bool checkIfInputIsInt(const std::string& s)
{
for (auto &c : s) {
if (!isdigit(c)) return false;
}
return true;
}
bool checkIfInputIsAlphabets(const std::string& s)
{
for (auto &c : s) {
if (!isalpha(c)) return false;
}
return true;
}
void pEnd(int numOfTimes = 1)
{
for (int i = 0; i < numOfTimes; i++) {
std::cout << "\n";
}
}
void shutdown()
{
pEnd();
std::cout << "Thank you for using GPA Calculator v" << version;
pEnd();
std::cout << "Please press ENTER to continue...";
std::cin.get();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
for (int i = 3; i >= 0; i--) {
std::cout << "Automatically shutting down in " << i << " seconds...";
std::this_thread::sleep_for(std::chrono::seconds(1));
if (i != 0) std::cout << "\r";
}
}
bool checkIfFileExist (const std::string& fileName)
{
struct stat buffer;
return (stat(fileName.c_str(), &buffer) == 0);
}
void saveToPC(const gpaHashMapStruc& oldGPAMap)
{
Json::Value newGPAMap;
Json::StreamWriterBuilder builder;
builder["indentation"] = " ";
for (auto it = oldGPAMap.begin(); it != oldGPAMap.end(); ++it) {
auto f = it->first; auto s = it->second;
newGPAMap["gpa"][f]["grade"] = std::get<0>(s);
newGPAMap["gpa"][f]["credit"] = std::get<1>(s);
}
std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
std::ofstream out(jsonFile);
writer->write(newGPAMap, &out);
out.close();
}
float gradeToFloat(std::string& grade)
{
if (!checkIfUppercase(grade)) uppercaseInput(grade);
auto it = gpaRef.find(grade);
if (it != gpaRef.end()) return it->second;
else return -1.0;
}
bool checkIfInputIsValidGrade(std::string& grade)
{
if (!checkIfUppercase(grade)) uppercaseInput(grade);
auto it = gpaRef.find(grade);
if (it != gpaRef.end()) return true;
else return false;
}
void printMsgWithNthPrec(const std::vector<std::string>& msgArr, const int prec)
{
std::cout << std::fixed << std::showpoint;
std::cout << std::setprecision(prec);
for (int i = 0; i < msgArr.size(); i++) {
try {
float num = std::stof(msgArr[i]);
std::cout << num;
} catch (std::invalid_argument& e) {
std::cout << msgArr[i];
}
}
pEnd();
}
void printMenu(const float& gpa, const bool& validJsonFile)
{
std::cout << "\n\n------------ Menu ------------\n\n";
std::string gpaString;
if (gpa < 0) gpaString = "N/A";
else gpaString = std::to_string(gpa);
std::vector<std::string> msgArr = { "> Current GPA: ", gpaString };
printMsgWithNthPrec(msgArr, 2);
pEnd();
std::cout << "1. Add new module results";
if (validJsonFile) {
pEnd();
std::cout << "2. Edit module results";
pEnd();
std::cout << "3. Remove module results";
pEnd();
std::cout << "4. View all module results";
}
pEnd();
std::cout << "F. Shutdown";
pEnd();
std::cout << "\n-------------------------------";
}
void readJsonGPAData(const gpaHashMapStruc& gpaMap)
{
pEnd();
std::cout << "----------------------------------------------\n\n";
std::cout << "Reading GPA data...\n\n";
for (auto it = gpaMap.begin(); it != gpaMap.end(); it++) {
auto moduleName = it->first; auto value = it->second;
std::cout << "- " << moduleName << " (" << std::get<1>(value) << "): " << std::get<0>(value) << "\n";
}
pEnd();
std::cout << "Format:\nModule Name (Max Credits): Your Grade\n";
std::cout << "\n----------------------------------------------\n";
}
float calculateGPA(const gpaHashMapStruc& gpaMap)
{
int totalCredits = 0;
int totalGrade = 0;
for(gpaHashMapStruc::const_iterator it = gpaMap.begin(); it != gpaMap.end(); it++) {
std::string grade = std::get<0>(it->second);
if (grade != "P") {
int credits = std::get<1>(it->second);
totalCredits += credits;
totalGrade += gradeToFloat(grade) * credits;
}
}
return totalGrade / (float)totalCredits;
}
void mainProcess()
{
bool jsonFileExist = checkIfFileExist(jsonFile);
bool jsonValid = false;
if (jsonFileExist) {
std::ifstream file(jsonFile);
bool parsed = reader.parse(file, root);
file.close();
if (!parsed){
std::cout << "\nError: Cannot parse json content...\n";
} else {
if (root["gpa"].isNull()) {
jsonValid = false;
std::cout << "\nError: gpa.json does not have the necessary information...\n";
} else jsonValid = true;
}
}
gpaHashMapStruc gpaMap;
float totalGPA = -1.0; // placeholder as if it's less than 0, it will print out N/A in the menu
if (jsonValid) {
Json::Value values = root["gpa"];
for(auto it = values.begin(); it != values.end(); it++) {
std::string moduleName = it.key().asString();
std::string grade = values[moduleName]["grade"].asString();
if (!checkIfUppercase(grade)) uppercaseInput(grade);
int credit = values[moduleName]["credit"].asInt();
gpaMap[moduleName] = std::make_tuple(grade, credit);
}
}
std::string userInput = "";
while (userInput != "F") {
totalGPA = calculateGPA(gpaMap);
printMenu(totalGPA, jsonValid);
std::cout << "\nPlease enter your desired command: ";
std::getline(std::cin, userInput); uppercaseInput(userInput);
if (userInput == "1") {
// add new module results
bool continueAdding = true;
while (continueAdding) {
std::string finalModuleName;
int finalCredit = 0;
std::string finalGrade;
// adding the name of the module
while (continueAdding) {
std::string moduleName;
bool addedModuleName = false;
std::cout << "\nPlease enter the module name (x to cancel): ";
std::getline(std::cin, moduleName); titleInput(moduleName);
if (moduleName == "X") {
continueAdding = false;
break;
}
if (gpaMap.find(moduleName) != gpaMap.end()) {
std::cout << "Error: Module name already exists...\n";
} else if (!moduleName.empty()) {
while (1) {
std::cout << "Are you sure that you would to add the module with the name, " << moduleName << "? (y/n): ";
std::string confirmInput;
std::getline(std::cin, confirmInput); uppercaseInput(confirmInput);
if (confirmInput == "Y") {
finalModuleName = moduleName;
addedModuleName = true;
break;
} else if (confirmInput == "N") {
break;
} else {
std::cout << "Invalid input...\n";
}
}
} else {
std::cout << "Error: Input cannot be empty...\n";
}
if (addedModuleName) break;
}
// adding the grade obtained by the user for that module
while (continueAdding) {
std::string moduleGrade;
bool addedGrade = false;
std::cout << "\nPlease enter your grade for \"" << finalModuleName << "\" (x to cancel): ";
std::getline(std::cin, moduleGrade); uppercaseInput(moduleGrade);
if (moduleGrade == "X") {
continueAdding = false;
break;
}
if (checkIfInputIsValidGrade(moduleGrade)) {
while (1) {
std::cout << "Are you sure that you would to add your grade, \"" << moduleGrade << "\", to the module, " << finalModuleName << "? (y/n): ";
std::string confirmInput;
std::getline(std::cin, confirmInput); uppercaseInput(confirmInput);
if (confirmInput == "Y") {
finalGrade = moduleGrade;
addedGrade = true;
break;
} else if (confirmInput == "N") {
break;
} else {
std::cout << "Invalid input...\n";
}
}
} else {
std::cout << "Invalid grade input...\n";
}
if (addedGrade) break;
}
// adding the module credits
while (continueAdding) {
std::string moduleCredit;
bool addedCredit = false;
std::cout << "\nPlease enter the number of credits for \"" << finalModuleName << "\" (x to cancel): ";
std::getline(std::cin, moduleCredit); uppercaseInput(moduleCredit);
if (moduleCredit == "X") {
continueAdding = false;
break;
}
if (checkIfInputIsInt(moduleCredit)) {
int moduleCreditNum = std::stoi(moduleCredit);
if (moduleCreditNum >= 0 || moduleCreditNum <= 99) {
while (1) {
std::string confirmInput;
std::cout << "Are you sure that you would to add the module credits of, " << moduleCredit << ", for the module, " << finalModuleName << "? (y/n): ";
std::getline(std::cin, confirmInput); uppercaseInput(confirmInput);
if (confirmInput == "Y") {
finalCredit = moduleCreditNum;
addedCredit = true;
break;
} else if (confirmInput == "N") {
break;
} else {
std::cout << "Invalid input...\n";
}
}
} else {
std::cout << "Credit input is either too high or is in the negative range...\n";
}
} else {
std::cout << "Invalid input...\n";
}
if (addedCredit) break;
}
if (continueAdding) {
std::cout << "\nAdded module, " << finalModuleName << ", with grade, " << finalGrade << ", and credits, " << finalCredit << ", to gpa.json...\n";
gpaMap[finalModuleName] = std::make_tuple(finalGrade, finalCredit);
saveToPC(gpaMap);
std::cout << "------------------------------------------------------------------------------------\n";
jsonValid = true;
}
}
} else if (userInput == "2" && jsonValid) {
// edit existing module result
bool readGPA = true;
while (1) {
if (readGPA) readJsonGPAData(gpaMap);
std::string moduleToEdit;
std::cout << "\nPlease enter the module name that you would to edit (X to cancel): ";
std::getline(std::cin, moduleToEdit); titleInput(moduleToEdit);
if (moduleToEdit == "X") break;
if (gpaMap.find(moduleToEdit) != gpaMap.end()) {
bool editedInfo = false;
std::string initialModName = moduleToEdit;
std::string initialGrade = std::get<0>(gpaMap[moduleToEdit]);
int initialCredit = std::get<1>(gpaMap[moduleToEdit]);
while (1) {
std::cout << "----------------------------------------------\n\n";
std::cout << "Currently editing " << moduleToEdit << "...\n";
std::cout << "Current grade: " << std::get<0>(gpaMap[moduleToEdit]) << "\n";
std::cout << "Current credit: " << std::get<1>(gpaMap[moduleToEdit]) << "\n\n";
std::cout << "Commands:\n";
std::cout << "\"n\" to edit the module name\n";
std::cout << "\"g\" to edit the grade\n";
std::cout << "\"c\" to edit the credit\n";
if (editedInfo) {
std::cout << "\"s\" to save changes\n";
std::cout << "\"b\" to revert changes\n";
}
std::cout << "\"x\" to cancel editing and return to menu\n";
std::cout << "\n----------------------------------------------\n";
std::string editCommand;
std::cout << "Enter command: ";
std::getline(std::cin, editCommand); uppercaseInput(editCommand);
if (editCommand == "X") break;
else if (editCommand == "N") {
while (1) {
std::string newModuleName;
std::cout << "Enter new module name (x to cancel): ";
std::getline(std::cin, newModuleName); titleInput(newModuleName);
if (gpaMap.find(newModuleName) != gpaMap.end()) {
std::cout << "Error: Module name already exists...\n";
} else if (newModuleName == "X") {
break;
} else if (!newModuleName.empty()) {
gpaMap[newModuleName] = gpaMap[moduleToEdit];
gpaMap.erase(moduleToEdit);
moduleToEdit = newModuleName;
editedInfo = true;
break;
} else {
std::cout << "Error: Input cannot be empty...\n";
}
}
} else if (editCommand == "G") {
while (1) {
std::string newGrade;
std::cout << "Enter new grade (x to cancel): ";
std::getline(std::cin, newGrade); uppercaseInput(newGrade);
if (newGrade == "X") {
break;
} else if (!checkIfInputIsValidGrade(newGrade)) {
std::cout << "Error: Invalid grade...\n";
} else {
std::get<0>(gpaMap[moduleToEdit]) = newGrade;
editedInfo = true;
break;
}
}
} else if (editCommand == "C") {
while (1) {
std::string newCredit;
std::cout << "Enter new credit (x to cancel): ";
std::getline(std::cin, newCredit); uppercaseInput(newCredit);
if (checkIfInputIsInt(newCredit)) {
int newCreditVal = std::stoi(newCredit);
if (newCreditVal >= 0 && newCreditVal <= 99) {
std::get<1>(gpaMap[moduleToEdit]) = newCreditVal;
editedInfo = true;
break;
} else {
std::cout << "Error: Credit input is either too high or is in the negative range...\n";
}
} else if (newCredit == "X") {
break;
} else {
std::cout << "Error: Invalid credit input or credit input was larger than 99...\n";
}
}
} else if (editCommand == "S" && editedInfo) {
std::cout << "Are you sure that you would to save the changes? (y/n): ";
std::string confirmSave;
std::getline(std::cin, confirmSave); uppercaseInput(confirmSave);
if (confirmSave == "Y") {
saveToPC(gpaMap);
editedInfo = false;
} else if (confirmSave == "N") {
std::cout << "Saving of changes aborted...\n";
} else {
std::cout << "Error: Invalid input...\n";
}
} else if (editCommand == "B" && editedInfo) {
std::cout << "Are you sure that you would to revert the changes? (y/n): ";
std::string confirmSave;
std::getline(std::cin, confirmSave); uppercaseInput(confirmSave);
if (confirmSave == "Y") {
gpaMap.erase(moduleToEdit);
gpaMap[initialModName] = std::make_tuple(initialGrade, initialCredit);
moduleToEdit = initialModName;
editedInfo = false;
} else if (confirmSave == "N") {
std::cout << "Reverting of changes aborted...\n";
} else {
std::cout << "Error: Invalid input...\n";
}
} else {
std::cout << "Invalid command. Please enter a valid command from the menu above.\n\n";
}
}
break;
} else {
std::cout << "Module not found!\n";
readGPA = false;
}
}
} else if (userInput == "3" && jsonValid) {
// remove module result
bool readGPA = true;
while (1) {
if (readGPA) readJsonGPAData(gpaMap);
std::string moduleToRemove;
std::cout << "\nPlease enter the module name that you would like to remove (X to cancel): ";
std::getline(std::cin, moduleToRemove); titleInput(moduleToRemove);
if (moduleToRemove == "X") break;
if (gpaMap.find(moduleToRemove) != gpaMap.end()) {
std::string confirmErase;
while (1) {
std::cout << "Are you sure you want to remove the module, " << moduleToRemove << "? (Y/N): ";
std::getline(std::cin, confirmErase); uppercaseInput(confirmErase);
if (confirmErase == "Y" || confirmErase == "N") break;
else std::cout << "Please enter \"Y\" or \"N\"\n";
}
if (confirmErase == "Y") {
gpaMap.erase(moduleToRemove);
std::cout << "Module " << moduleToRemove << " has been removed.\n";
saveToPC(gpaMap);
} else std::cout << "Module " << moduleToRemove << " will NOT be removed.\n";
readGPA = true;
} else {
std::cout << "Module not found!\n";
readGPA = false;
}
}
} else if (userInput == "4" && jsonValid) {
// read all module results
readJsonGPAData(gpaMap);
} else if (userInput != "F") {
std::cout << "Invalid command input, please enter a valid command from the menu above.\n";
}
}
}
void logError(std::string errorMessage)
{
if (!checkIfFileExist(errorLogFile)) {
std::ofstream errorLogFileStream;
errorLogFileStream.open(errorLogFile);
errorLogFileStream << "GPA Calculator v" << version << " Error Logs\n\n";
errorLogFileStream.close();
}
std::ofstream errorLog;
errorLog.open(errorLogFile, std::ios::app);
errorLog << "\nError occurred at ";
time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
errorLog << std::put_time(localtime(&now), "%F %T") << "\n";
errorLog << "Error message: ";
errorLog << errorMessage << "\n";
errorLog.close();
}
int main()
{
std::cout << "========================== GPA Calculator v" << version << " ==========================\n";
std::cout << "================ https://github.com/KJHJason/GPACalculator ================\n";
std::cout << "============================ Author: KJHJason =============================\n";
std::cout << "============================== License: MIT ===============================\n";
try {
mainProcess();
} catch(const std::runtime_error& re) {
std::cout << "\nRuntime error encountered: " << re.what();
pEnd();
logError(re.what());
shutdown();
return 1;
} catch (const std::exception& e) {
std::cout << "\nError encountered: " << e.what();
pEnd();
logError(e.what());
shutdown();
return 1;
} catch(...) {
std::cout << "\nUnknown error encountered.";
pEnd();
shutdown();
return 1;
}
shutdown();
return 0;
}