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
|
#include <iostream>
#include <string>
#include <map>
#include <array>
#include <limits>
#include <sstream>
constexpr std::array topics {"English", "French", "Sesotho", "Maths", "Science", "Social"};
unsigned getInt(const std::string& prm)
{
unsigned i {};
while ((std::cout << prm) && !(std::cin >> i)) {
std::cout << "Invalid integer\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return i;
}
class Students {
public:
bool getInput() {
Record rec(newRoll());
const std::string studNum {"S" + std::to_string(rec.snum)};
std::cout << "\nEnter data for student " << studNum << '\n';
std::cout << "Name (CR to finish): ";
std::getline(std::cin, rec.name);
if (rec.name.empty())
return false;
std::cout << "Grade/Class: ";
std::getline(std::cin, rec.grade);
for (size_t t = 0; t < topics.size(); ++t) {
std::ostringstream oss;
oss << "Enter mark for " << topics[t] << " out of 100: ";
do
rec.marks[t] = getInt(oss.str());
while ((rec.marks[t] > 100) && (std::cout << "Invalid mark\n"));
}
students[studNum] = rec;
return true;
}
friend std::ostream& operator<<(std::ostream& os, const Students& st);
private:
struct Record {
unsigned snum {};
std::string name;
std::string grade;
std::array<unsigned, topics.size()> marks {};
Record() {}
Record(unsigned roll) : snum(roll) {}
};
std::map<std::string, Record> students;
unsigned newRoll() const { return students.empty() ? 1001 : students.rbegin()->second.snum + 1; }
static std::ostream& disRec(std::ostream& os, const Record& rec) {
os << "Name: " << rec.name << '\n' << "Grade/Class: " << rec.grade << '\n';
for (size_t t = 0; t < topics.size(); ++t)
os << "Mark scored for " << topics[t] << " is " << rec.marks[t] << '\n';
return os;
}
};
std::ostream& operator<<(std::ostream& os, const Students& st)
{
for (const auto& s : st.students) {
os << "\nStudent " << s.first << '\n';
Students::disRec(os, s.second);
}
return os;
}
unsigned menu()
{
std::cout << '\n';
std::cout << "1. Add Student Record\n";
std::cout << "2. Display All Students\n";
std::cout << "0. Exit\n";
return getInt("Enter Option: ");
}
int main()
{
Students students;
while (true)
switch (menu()) {
case 1:
while (students.getInput());
break;
case 2:
std::cout << students << '\n';
break;
case 0:
return 0;
default:
std::cout << "Unknown option\n";
break;
}
}
|