C++编写的简单示例,实现一个简单的学生管理系统,可以进行添加学生、查找学生、显示学生信息和退出程序的操作
创建一个Student.cpp源文件,实现Student类的成员函数,代码如下:
#include <iostream>
#include "Student.h"
Student::Student() {
name = "";
age = 0;
id = "";
score = 0;
}
Student::Student(std::string name, int age, std::string id, double score) {
this->name = name;
this->age = age;
this->id = id;
this->score = score;
}
void Student::setName(std::string name) {
this->name = name;
}
std::string Student::getName() {
return name;
}
void Student::setAge(int age) {
this->age = age;
}
int Student::getAge() {
return age;
}
void Student::setId(std::string id) {
this->id = id;
}
std::string Student::getId() {
return id;
}
void Student::setScore(double score) {
this->score = score;
}
double Student::getScore() {
return score;
}
void Student::display() {
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "ID: " << id << std::endl;
std::cout << "Score: " << score << std::endl;
}
Student student(name, age, id, score);
students.push_back(student);
cout << "Added student:" << endl;
student.display();
}
void findStudent() {
string id;
cout << "Enter student ID to find: ";
cin >> id;
c
Copy code
vector<Student>::iterator it;
it = find_if(students.begin(), students.end(), [&](const Student& student) {
return student.getId() == id;
});
if (it != students.end()) {
cout << "Found student:" << endl;
it->display();
} else {
cout << "Student not found." << endl;
}
}
void displayStudents() {
cout << "All students:" << endl;
for (vector<Student>::iterator it = students.begin(); it != students.end(); it++) {
it->display();
}
}
int main() {
int choice = 0;
while (choice != 4) {
cout << "1. Add student" << endl;
cout << "2. Find student" << endl;
cout << "3. Display all students" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
c
Copy code
switch (choice) {
case 1:
addStudent();
break;
case 2:
findStudent();
break;
case 3:
displayStudents();
break;
case 4:
cout << "Exiting program..." << endl;
break;
default:
cout << "Invalid choice. Please try again." << endl;
break;
}
}
return 0;
}
在main函数中,我们使用一个while循环来不断接受用户的输入,并根据用户的选择调用对应的函数来执行添加、查找或显示学生信息的操作。具体实现中,我们使用了一个vector来存储学生对象,并使用STL中的find_if函数来查找学生对象,使用迭代器来遍历vector并显示所有学生信息。以上就是一个简单的用C++实现的学生管理系统的示例代码。