c++
时间: 2023-07-01 14:22:06 浏览: 41
好的,下面是一个简单的示例代码:
```cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Student {
public:
int id;
string name;
float score;
void output() {
cout << "id: " << id << ", name: " << name << ", score: " << score << endl;
}
void input() {
cout << "Enter id: ";
cin >> id;
cout << "Enter name: ";
cin >> name;
cout << "Enter score: ";
cin >> score;
}
};
int main() {
const char* filename = "Record.dat";
int num = 3;
Student students[num];
// input student data
for (int i = 0; i < num; i++) {
cout << "Enter student " << i + 1 << " information:\n";
students[i].input();
}
// write student data to file
ofstream ofs(filename, ios::binary);
for (int i = 0; i < num; i++) {
ofs.write(reinterpret_cast<const char*>(&students[i]), sizeof(Student));
}
ofs.close();
// read student data from file
ifstream ifs(filename, ios::binary);
Student s;
while (ifs.read(reinterpret_cast<char*>(&s), sizeof(Student))) {
s.output();
}
ifs.close();
return 0;
}
```
这个示例程序中,我们定义了一个 `Student` 类,包含了学号、姓名和成绩三个数据成员,以及 `input()` 和 `output()` 两个成员函数用于输入和输出学生信息。在 `main()` 函数中,我们先输入了若干个学生的信息,然后将它们写入到文件 `Record.dat` 中。接着,我们从文件中读取学生信息,并输出到屏幕上。