You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
2.4 KiB

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
class Student {
private:
std::string name;
int age;
int studentNumber;
public:
Student(std::string n, int a, int sn) : name(n), age(a), studentNumber(sn) {}
std::string getName() const {
return name;
}
int getAge() const {
return age;
}
int getStudentNumber() const {
return studentNumber;
}
};
void saveData(const std::vector<Student>& students) {
std::ofstream file("student_data.txt");
if (file.is_open()) {
for (const auto& student : students) {
file << student.getName() << " " << student.getAge() << " " << student.getStudentNumber() << std::endl;
}
file.close();
} else {
std::cout << "Error: Unable to open file for writing." << std::endl;
}
}
void readData(std::vector<Student>& students) {
std::ifstream file("student_data.txt");
if (file.is_open()) {
std::string name;
int age, studentNumber;
while (file >> name >> age >> studentNumber) {
students.push_back(Student(name, age, studentNumber));
}
file.close();
} else {
std::cout << "No existing data found." << std::endl;
}
}
int main() {
std::vector<Student> students;
// 读取文件中已存在的数据
readData(students);
int choice;
do {
std::cout << "1. Add student\n";
std::cout << "2. Delete student\n";
std::cout << "3. Update student\n";
std::cout << "4. View all students\n";
std::cout << "5. Save and exit\n";
std::cin >> choice;
switch (choice) {
case 1: {
std::string name;
int age, studentNumber;
std::cout << "Enter name, age, and student number: ";
std::cin >> name >> age >> studentNumber;
students.push_back(Student(name, age, studentNumber));
break;
}
case 2: {
// Delete student
// Your code to delete a student here
break;
}
case 3: {
// Update student
// Your code to update a student here
break;
}
case 4: {
// View all students
for (const auto& student : students) {
std::cout << student.getName() << " " << student.getAge() << " " << student.getStudentNumber() << std::endl;
}
break;
}
case 5: {
// Save and exit
saveData(students);
std::cout << "Data saved. Goodbye!" << std::endl;
break;
}
default:
std::cout << "Invalid choice!" << std::endl;
}
} while (choice != 5);
return 0;
}