用C++写一个学生信息管理系统,要求用到类、vector容器,能把数据存到txt文件中,并从中读取数据,学生信息包括学号、姓名、性别、班级、家庭地址
时间: 2023-07-04 08:08:48 浏览: 86
好的,下面是一个简单的学生信息管理系统的代码,它使用了C++中的类和vector容器,可以将学生信息存储到txt文件中,并从文件中读取数据:
```c++
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
// 定义学生类
class Student {
public:
int id; // 学号
string name; // 姓名
string gender; // 性别
string className; // 班级
string address; // 家庭地址
// 构造函数
Student(int id = 0, string name = "", string gender = "", string className = "", string address = "") {
this->id = id;
this->name = name;
this->gender = gender;
this->className = className;
this->address = address;
}
};
// 定义学生信息管理类
class StudentManager {
private:
vector<Student> students; // 保存学生信息的vector容器
public:
// 添加学生信息
void addStudent(Student student) {
students.push_back(student);
}
// 显示所有学生信息
void showAllStudents() {
cout << "学号\t姓名\t性别\t班级\t家庭地址" << endl;
for (int i = 0; i < students.size(); i++) {
Student student = students[i];
cout << student.id << "\t" << student.name << "\t" << student.gender << "\t"
<< student.className << "\t" << student.address << endl;
}
}
// 保存学生信息到文件
void saveToFile(string filename) {
ofstream outfile(filename);
for (int i = 0; i < students.size(); i++) {
Student student = students[i];
outfile << student.id << "," << student.name << "," << student.gender << ","
<< student.className << "," << student.address << endl;
}
outfile.close();
}
// 从文件中读取学生信息
void readFromFile(string filename) {
ifstream infile(filename);
string line;
while (getline(infile, line)) {
int pos1 = line.find(",");
int pos2 = line.find(",", pos1 + 1);
int pos3 = line.find(",", pos2 + 1);
int pos4 = line.find(",", pos3 + 1);
int id = stoi(line.substr(0, pos1));
string name = line.substr(pos1 + 1, pos2 - pos1 - 1);
string gender = line.substr(pos2 + 1, pos3 - pos2 - 1);
string className = line.substr(pos3 + 1, pos4 - pos3 - 1);
string address = line.substr(pos4 + 1);
Student student(id, name, gender, className, address);
students.push_back(student);
}
infile.close();
}
};
int main() {
StudentManager manager;
manager.readFromFile("students.txt");
while (true) {
cout << "请选择操作:" << endl;
cout << "1. 添加学生信息" << endl;
cout << "2. 显示所有学生信息" << endl;
cout << "3. 保存学生信息到文件" << endl;
cout << "4. 退出程序" << endl;
int choice;
cin >> choice;
switch (choice) {
case 1:
cout << "请输入学生信息(学号 姓名 性别 班级 家庭地址):" << endl;
int id;
string name, gender, className, address;
cin >> id >> name >> gender >> className >> address;
manager.addStudent(Student(id, name, gender, className, address));
break;
case 2:
manager.showAllStudents();
break;
case 3:
manager.saveToFile("students.txt");
break;
case 4:
return 0;
default:
cout << "输入有误,请重新选择" << endl;
}
}
return 0;
}
```
注意,上面的代码中假设学生信息以逗号分隔,并且每个学生信息占据一行。在实际使用中,我们应该根据实际情况修改代码以适应不同的数据格式。
阅读全文