宿舍管理系统c++简易版
时间: 2023-11-30 17:42:33 浏览: 145
宿舍管理系统(C++版)
5星 · 资源好评率100%
以下是一个简单的宿舍管理系统的C++代码示例,它可以实现添加、删除、修改和查询学生信息的功能:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
// 定义学生结构体
struct Student {
string name;
string id;
string room;
};
// 定义全局变量
vector<Student> students;
// 读取学生信息文件
void readStudents() {
ifstream fin("students.txt");
if (!fin) {
cout << "无法打开文件!" << endl;
return;
}
while (!fin.eof()) {
Student student;
fin >> student.name >> student.id >> student.room;
students.push_back(student);
}
fin.close();
}
// 保存学生信息到文件
void saveStudents() {
ofstream fout("students.txt");
if (!fout) {
cout << "无法打开文件!" << endl;
return;
}
for (int i = 0; i < students.size(); i++) {
fout << students[i].name << " " << students[i].id << " " << students[i].room << endl;
}
fout.close();
}
// 添加学生信息
void addStudent() {
Student student;
cout << "请输入学生姓名:";
cin >> student.name;
cout << "请输入学生学号:"; cin >> student.id;
cout << "请输入学生宿舍号:";
cin >> student.room;
students.push_back(student);
saveStudents();
cout << "添加成功!" << endl;
}
// 删除学生信息
void deleteStudent() {
string id;
cout << "请输入要删除的学生学号:";
cin >> id;
for (int i = 0; i < students.size(); i++) {
if (students[i].id == id) {
students.erase(students.begin() + i);
saveStudents();
cout << "删除成功!" << endl;
return;
}
}
cout << "未找到该学生!" << endl;
}
// 修改学生信息
void modifyStudent() {
string id;
cout << "请输入要修改的学生学号:";
cin >> id;
for (int i = 0; i < students.size(); i++) {
if (students[i].id == id) {
cout << "请输入学生姓名:";
cin >> students[i].name;
cout << "请输入学生宿舍号:";
cin >> students[i].room;
saveStudents();
cout << "修改成功!" << endl;
return;
}
}
cout << "未找到该学生!" << endl;
}
// 查询学生信息
void queryStudent() {
string id;
cout << "请输入要查询的学生学号:";
cin >> id;
for (int i = 0; i < students.size(); i++) {
if (students[i].id == id) {
cout << "姓名:" << students[i].name << endl;
cout << "学号:" << students[i].id << endl;
cout << "宿舍号:" << students[i].room << endl;
return;
}
}
cout << "未找到该学生!" << endl;
}
// 显示菜单
void showMenu() {
cout << "======================" << endl;
cout << "宿舍管理系统" << endl;
cout << "1. 添加学生信息" << endl;
cout << "2. 删除学生信息" << endl;
cout << "3. 修改学生信息" << endl;
cout << "4. 查询学生信息" << endl;
cout << "0. 退出系统" << endl;
cout << "======================" << endl;
}
int main() {
readStudents();
while (true) {
showMenu();
int choice;
cout << "请输入操作编号:";
cin >> choice;
switch (choice) {
case 1:
addStudent();
break;
case 2:
deleteStudent();
break;
case 3:
modifyStudent();
break;
case 4:
queryStudent();
break;
case 0:
cout << "谢谢使用!" << endl;
return 0;
default:
cout << "输入有误,请重新输入!" << endl;
break;
}
}
return 0;
}
```
阅读全文