首页 新闻 会员 周边 捐助

为什么第十四行报错

0
悬赏园豆:10 [已解决问题] 解决于 2024-03-03 13:45

include <iostream>

include <fstream>

include <string>

include <vector>

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;

}

深秋晨风的主页 深秋晨风 | 初学一级 | 园豆:51
提问于:2024-02-23 16:11
< >
分享
最佳答案
0

可能是权限、环境问题,换个目录位置

收获园豆:6
hardersen | 菜鸟二级 |园豆:206 | 2024-02-26 17:46
其他回答(1)
0

在C++中,包含头文件时应该使用 #include 而不是 include。因此,您需要将第14行以及后续的 include 改为 #include,如下所示:

cpp
Copy code

include <iostream>

include <fstream>

include <string>

include <vector>

这样修改之后,您的程序就可以正确地包含所需的头文件,不会再出现编译错误。

收获园豆:4
Technologyforgood | 园豆:7603 (大侠五级) | 2024-02-25 13:21
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册