用c++写学生选修课程管理
时间: 2023-07-01 16:08:34 浏览: 55
好的,以下是一个简单的学生选修课程管理系统的 C++ 代码示例:
```c++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// 课程结构体
struct Course {
string name; // 课程名称
int credit; // 学分
};
// 学生结构体
struct Student {
string name; // 姓名
string id; // 学号
vector<Course> courses; // 选修课程
};
// 添加课程函数
void addCourse(vector<Course>& courses) {
Course course;
cout << "请输入课程名称:";
cin >> course.name;
cout << "请输入课程学分:";
cin >> course.credit;
courses.push_back(course);
}
// 添加学生函数
void addStudent(vector<Student>& students) {
Student student;
cout << "请输入学生姓名:";
cin >> student.name;
cout << "请输入学生学号:";
cin >> student.id;
students.push_back(student);
}
// 选课函数
void selectCourse(vector<Student>& students, vector<Course>& courses) {
string id;
cout << "请输入学生学号:";
cin >> id;
for (int i = 0; i < students.size(); i++) {
if (students[i].id == id) {
cout << "请选择课程(输入课程序号):" << endl;
for (int j = 0; j < courses.size(); j++) {
cout << j + 1 << ". " << courses[j].name << "(" << courses[j].credit << "学分)" << endl;
}
int choice;
cin >> choice;
students[i].courses.push_back(courses[choice - 1]);
cout << "选课成功!" << endl;
return;
}
}
cout << "学生不存在!" << endl;
}
// 查看学生选课情况函数
void showCourse(vector<Student>& students) {
string id;
cout << "请输入学生学号:";
cin >> id;
for (int i = 0; i < students.size(); i++) {
if (students[i].id == id) {
cout << students[i].name << "同学选修了以下课程:" << endl;
for (int j = 0; j < students[i].courses.size(); j++) {
cout << students[i].courses[j].name << "(" << students[i].courses[j].credit << "学分)" << endl;
}
return;
}
}
cout << "学生不存在!" << endl;
}
int main() {
vector<Course> courses; // 课程列表
vector<Student> students; // 学生列表
while (true) {
int choice;
cout << "请选择操作:" << endl;
cout << "1. 添加课程" << endl;
cout << "2. 添加学生" << endl;
cout << "3. 选课" << endl;
cout << "4. 查看选课情况" << endl;
cout << "5. 退出" << endl;
cin >> choice;
switch (choice) {
case 1:
addCourse(courses);
break;
case 2:
addStudent(students);
break;
case 3:
selectCourse(students, courses);
break;
case 4:
showCourse(students);
break;
case 5:
return 0;
default:
cout << "输入有误,请重新输入!" << endl;
break;
}
}
}
```
这个程序实现了添加课程、添加学生、选课和查看学生选课情况等基本功能。当然,这只是一个简单的示例,实际上还有很多细节需要考虑,比如输入合法性检查、数据持久化等等。