数据结构课程设计c++宿舍管理系统
时间: 2023-12-18 14:05:13 浏览: 40
以下是一个简单的C++宿舍管理系统的示例,使用了链表来存储学生信息和宿舍信息:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// 学生信息结构体
struct Student {
string name; // 姓名
int age; // 年龄
string gender; // 性别
string dorm; // 宿舍号
Student* next; // 指向下一个学生的指针
};
// 宿舍信息结构体
struct Dorm {
string dorm; // 宿舍号
int capacity; // 容纳人数
int count; // 当前人数
Dorm* next; // 指向下一个宿舍的指针
};
// 添加学生信息
void addStudent(Student*& head) {
Student* p = new Student;
cout << "请输入学生姓名:";
cin >> p->name;
cout << "请输入学生年龄:";
cin >> p->age;
cout << "请输入学生性别:";
cin >> p->gender;
cout << "请输入学生宿舍号:";
cin >> p->dorm;
p->next = head;
head = p;
}
// 添加宿舍信息
void addDorm(Dorm*& head) {
Dorm* p = new Dorm;
cout << "请输入宿舍号:";
cin >> p->dorm;
cout << "请输入宿舍容纳人数:";
cin >> p->capacity;
p->count = 0;
p->next = head;
head = p;
}
// 显示学生信息
void showStudent(Student* head) {
cout << "姓名\t年龄\t性别\t宿舍号" << endl;
while (head != NULL) {
cout << head->name << "\t" << head->age << "\t" << head->gender << "\t" << head->dorm << endl;
head = head->next;
}
}
// 显示宿舍信息
void showDorm(Dorm* head) {
cout << "宿舍号\t容纳人数\t当前人数" << endl;
while (head != NULL) {
cout << head->dorm << "\t" << head->capacity << "\t" << head->count << endl;
head = head->next;
}
}
// 保存学生信息到文件
void saveStudent(Student* head) {
ofstream outfile("student.txt");
while (head != NULL) {
outfile << head->name << " " << head->age << " " << head->gender << " " << head->dorm << endl;
head = head->next;
}
outfile.close();
}
// 保存宿舍信息到文件
void saveDorm(Dorm* head) {
ofstream outfile("dorm.txt");
while (head != NULL) {
outfile << head->dorm << " " << head->capacity << " " << head->count << endl;
head = head->next;
}
outfile.close();
}
// 从文件中读取学生信息
void loadStudent(Student*& head) {
ifstream infile("student.txt");
while (!infile.eof()) {
Student* p = new Student;
infile >> p->name >> p->age >> p->gender >> p->dorm;
p->next = head;
head = p;
}
infile.close();
}
// 从文件中读取宿舍信息
void loadDorm(Dorm*& head) {
ifstream infile("dorm.txt");
while (!infile.eof()) {
Dorm* p = new Dorm;
infile >> p->dorm >> p->capacity >> p->count;
p->next = head;
head = p;
}
infile.close();
}
int main() {
Student* studentHead = NULL;
Dorm* dormHead = NULL;
loadStudent(studentHead);
loadDorm(dormHead);
int choice;
do {
cout << "请选择操作:" << endl;
cout << "1. 添加学生信息" << endl;
cout << "2. 添加宿舍信息" << endl;
cout << "3. 显示学生信息" << endl;
cout << "4. 显示宿舍信息" << endl;
cout << "5. 保存信息到文件" << endl;
cout << "6. 退出" << endl;
cin >> choice;
switch (choice) {
case 1:
addStudent(studentHead);
break;
case 2:
addDorm(dormHead);
break;
case 3:
showStudent(studentHead);
break;
case 4:
showDorm(dormHead);
break;
case 5:
saveStudent(studentHead);
saveDorm(dormHead); break;
case 6:
break;
default:
cout << "无效的选择,请重新输入!" << endl;
break;
}
} while (choice != 6);
return 0;
}
```