struct Student {
std::string name;
int score;
};
void saveData(const std::vector<Student>& students) {
std::ofstream file("data.txt");
if (file.is_open()) {
for (const auto& student : students) {
file << student.name << " " << student.score << std::endl;
}
file.close();
} else {
std::cerr << "Error: Unable to open file for writing." << std::endl;
}
}
std::vector<Student> loadData() {
std::vector<Student> students;
std::ifstream file("data.txt");
if (file.is_open()) {
std::string name;
int score;
while (file >> name >> score) {
students.push_back(Student{name, score});
}
file.close();
} else {
std::cerr << "Error: Unable to open file for reading." << std::endl;
}
return students;
}
void displayMenu() {
std::cout << "1. Add Student" << std::endl;
std::cout << "2. Display Scores" << std::endl;
std::cout << "3. Exit" << std::endl;
}
void addStudent(std::vector<Student>& students) {
Student newStudent;
std::cout << "Enter student's name: ";
std::cin >> newStudent.name;
std::cout << "Enter student's score: ";
std::cin >> newStudent.score;
students.push_back(newStudent);
}
void displayScores(const std::vector<Student>& students) {
std::cout << "Student Scores:" << std::endl;
for (const auto& student : students) {
std::cout << student.name << ": " << student.score << std::endl;
}
}
int main() {
std::vector<Student> students = loadData();
int choice;
do {
displayMenu();
std::cout << "Enter your choice: ";
std::cin >> choice;
switch (choice) {
case 1:
addStudent(students);
break;
case 2:
displayScores(students);
break;
case 3:
saveData(students);
std::cout << "Exiting program." << std::endl;
break;
default:
std::cout << "Invalid choice. Please try again." << std::endl;
}
} while (choice != 3);
return 0;
}
可能是权限、环境问题,换个目录位置
在C++中,包含头文件时应该使用 #include 而不是 include。因此,您需要将第14行以及后续的 include 改为 #include,如下所示:
cpp
Copy code
这样修改之后,您的程序就可以正确地包含所需的头文件,不会再出现编译错误。