用c++ 定义一个 Student 类,其中包含学号、姓名、成绩数据成员。建立若干个 Student 类 对象,将它们保存到文件 Record.dat 中,然后显示文件中的内容。
时间: 2024-02-21 11:01:46 浏览: 28
可以按照以下步骤来实现:
1. 定义一个 Student 类,包含学号、姓名、成绩数据成员:
```c++
class Student {
public:
int id;
string name;
double score;
void display() {
cout << "ID: " << id << ", Name: " << name << ", Score: " << score << endl;
}
};
```
2. 建立若干个 Student 对象并保存到文件中:
```c++
ofstream outfile("Record.dat", ios::binary);
if (!outfile) {
cout << "Failed to open file!" << endl;
return 0;
}
Student s1 = { 1001, "Alice", 85.5 };
Student s2 = { 1002, "Bob", 92.0 };
Student s3 = { 1003, "Charlie", 78.5 };
outfile.write((char*)&s1, sizeof(s1));
outfile.write((char*)&s2, sizeof(s2));
outfile.write((char*)&s3, sizeof(s3));
outfile.close();
```
3. 从文件中读取 Student 对象并显示:
```c++
ifstream infile("Record.dat", ios::binary);
if (!infile) {
cout << "Failed to open file!" << endl;
return 0;
}
Student rec;
while (infile.read((char*)&rec, sizeof(rec))) {
rec.display();
}
infile.close();
```
完整代码如下:
```c++
#include <iostream>
#include <fstream>
using namespace std;
class Student {
public:
int id;
string name;
double score;
void display() {
cout << "ID: " << id << ", Name: " << name << ", Score: " << score << endl;
}
};
int main() {
ofstream outfile("Record.dat", ios::binary);
if (!outfile) {
cout << "Failed to open file!" << endl;
return 0;
}
Student s1 = { 1001, "Alice", 85.5 };
Student s2 = { 1002, "Bob", 92.0 };
Student s3 = { 1003, "Charlie", 78.5 };
outfile.write((char*)&s1, sizeof(s1));
outfile.write((char*)&s2, sizeof(s2));
outfile.write((char*)&s3, sizeof(s3));
outfile.close();
ifstream infile("Record.dat", ios::binary);
if (!infile) {
cout << "Failed to open file!" << endl;
return 0;
}
Student rec;
while (infile.read((char*)&rec, sizeof(rec))) {
rec.display();
}
infile.close();
return 0;
}
```