ADD file via upload

main
pg7v3a8kq 6 months ago
parent 2fa7fc7cfc
commit 53f566dde7

@ -0,0 +1,107 @@
#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;
}
Loading…
Cancel
Save