用C++编写
时间: 2023-07-11 17:17:02 浏览: 78
用c++编写的游戏大全
以下是一个使用C++编写的学生成绩文件管理代码示例:
```cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
class Student {
private:
string name;
int grade;
public:
Student(string n, int g) {
name = n;
grade = g;
}
string get_name() {
return name;
}
int get_grade() {
return grade;
}
};
class GradeBook {
private:
vector<Student> students;
public:
void add_student(Student s) {
students.push_back(s);
}
void remove_student(Student s) {
for (int i = 0; i < students.size(); i++) {
if (students[i].get_name() == s.get_name()) {
students.erase(students.begin() + i);
break;
}
}
}
void save_grades(string filename) {
ofstream fout(filename);
for (int i = 0; i < students.size(); i++) {
fout << students[i].get_name() << "," << students[i].get_grade() << endl;
}
fout.close();
}
void load_grades(string filename) {
ifstream fin(filename);
string line;
while (getline(fin, line)) {
string name = line.substr(0, line.find(","));
int grade = stoi(line.substr(line.find(",") + 1));
Student s(name, grade);
add_student(s);
}
fin.close();
}
void print_grades() {
for (int i = 0; i < students.size(); i++) {
cout << students[i].get_name() << ": " << students[i].get_grade() << endl;
}
}
};
int main() {
GradeBook book;
// Add some students
book.add_student(Student("Alice", 90));
book.add_student(Student("Bob", 80));
book.add_student(Student("Charlie", 70));
// Save the grades to a file
book.save_grades("grades.txt");
// Remove a student
book.remove_student(Student("Bob", 80));
// Load the grades from the file
book.load_grades("grades.txt");
// Print the grades
book.print_grades();
return 0;
}
```
该代码包含两个类:`Student` 表示学生对象,包含姓名和成绩属性,`GradeBook` 表示成绩册对象,包含学生列表以及添加、删除、保存、加载和打印学生成绩的方法。
你可以根据自己的需求进行修改和扩展。
阅读全文