Untitled
unknown
plain_text
10 days ago
2.4 kB
2
Indexable
Never
#include <iostream> #include <string> class Student { public: Student(int id, const std::string& name) : id(id), name(name) {} int getId() const { return id; } const std::string& getName() const { return name; } private: int id; std::string name; }; class Course { public: Course(const std::string& courseName, int capacity) : courseName(courseName), maxCapacity(capacity), enrolledCount(0) {} bool enrollStudent(const Student& student) { if (enrolledCount < maxCapacity) { enrolledStudents[enrolledCount++] = student; std::cout << student.getName() << " has been enrolled in " << courseName << ".\n"; return true; } else { std::cout << "Enrollment failed: " << courseName << " is at full capacity.\n"; return false; } } bool withdrawStudent(int studentId) { for (int i = 0; i < enrolledCount; ++i) { if (enrolledStudents[i].getId() == studentId) { std::cout << enrolledStudents[i].getName() << " has withdrawn from " << courseName << ".\n"; enrolledStudents[i] = enrolledStudents[--enrolledCount]; // Replace with last student return true; } } std::cout << "Withdrawal failed: Student not found in " << courseName << ".\n"; return false; } void listEnrolledStudents() const { std::cout << "Students enrolled in " << courseName << ":\n"; for (int i = 0; i < enrolledCount; ++i) { std::cout << enrolledStudents[i].getName() << " (ID: " << enrolledStudents[i].getId() << ")\n"; } } private: std::string courseName; int maxCapacity; int enrolledCount; Student enrolledStudents[10]; // Assuming a maximum of 10 students for simplicity }; int main() { Course course1("Computer Science 101", 3); Student student1(1, "Alice"); Student student2(2, "Bob"); Student student3(3, "Charlie"); Student student4(4, "David"); course1.enrollStudent(student1); course1.enrollStudent(student2); course1.enrollStudent(student3); course1.enrollStudent(student4); // Should fail due to capacity course1.listEnrolledStudents(); course1.withdrawStudent(2); // Bob withdraws course1.listEnrolledStudents(); return 0; }
Leave a Comment