diff --git a/untitled1.cpp b/untitled1.cpp new file mode 100644 index 0000000..f8cbb84 --- /dev/null +++ b/untitled1.cpp @@ -0,0 +1,107 @@ +#include +#include +#include +#include + +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& 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& 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 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; +}