以下是一个简单的学生管理系统的C++代码示例:
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
struct Student {
string name;
int age;
string major;
};
vector<Student> students;
void addStudent() {
Student student;
cout << "请输入学生姓名:";
cin >> student.name;
cout << "请输入学生年龄:";
cin >> student.age;
cout << "请输入学生专业:";
cin >> student.major;
students.push_back(student);
cout << "添加成功!" << endl;
}
void displayStudent(const Student& student) {
cout << "姓名:" << student.name << endl;
cout << "年龄:" << student.age << endl;
cout << "专业:" << student.major << endl;
}
void displayAllStudents() {
if (students.empty()) {
cout << "暂无学生信息!" << endl;
return;
}
for (const auto& student : students) {
displayStudent(student);
cout << "-----------------------" << endl;
}
}
void searchStudent() {
string name;
cout << "请输入要查找的学生姓名:";
cin >> name;
for (const auto& student : students) {
if (student.name == name) {
displayStudent(student);
return;
}
}
cout << "未找到该学生!" << endl;
}
void deleteStudent() {
string name;
cout << "请输入要删除的学生姓名:";
cin >> name;
for (auto it = students.begin(); it != students.end(); ++it) {
if (it->name == name) {
students.erase(it);
cout << "删除成功!" << endl;
return;
}
}
cout << "未找到该学生!" << endl;
}
bool compareByName(const Student& s1, const Student& s2) {
return s1.name < s2.name;
}
void sortStudentsByName() {
sort(students.begin(), students.end(), compareByName);
cout << "按姓名排序成功!" << endl;
}
void saveToFile() {
ofstream file("students.txt");
for (const auto& student : students) {
file << "姓名:" << student.name << endl;
file << "年龄:" << student.age << endl;
file << "专业:" << student.major << endl;
file << "-----------------------" << endl;
}
file.close();
cout << "保存成功!" << endl;
}
int main() {
int choice;
while (true) {
cout << "1. 添加学生信息" << endl;
cout << "2. 修改学生信息" << endl; // 根据需要自行实现
cout << "3. 删除学生信息" << endl;
cout << "4. 按姓名排序" << endl;
cout << "5. 查找学生信息" << endl;
cout << "6. 显示所有学生信息" << endl;
cout << "7. 保存学生信息到文件" << endl;
cout << "0. 退出程序" << endl;
cout << "请输入您的选择:";
cin >> choice;
switch (choice) {
case 1:
addStudent();
break;
case 2:
// 实现修改学生信息的功能
break;
case 3:
deleteStudent();
break;
case 4:
sortStudentsByName();
break;
case 5:
searchStudent();
break;
case 6:
displayAllStudents();
break;
case 7:
saveToFile();
break;
case 0:
cout << "程序已退出!" << endl;
return 0;
default:
cout << "无效选择!" << endl;
}
}
return 0;
}
以上代码是一个简单的学生管理系统,实现了添加、删除、按姓名排序、查找、显示和保存学生信息的功能。根据需要,还可以进一步完善代码,实现修改学生信息的功能等。