用c++从二进制文件 record.dat 中读取姓名和成绩,并显示出来。
时间: 2024-02-21 19:01:42 浏览: 156
可以按照以下步骤来实现:
1. 定义一个结构体来存储姓名和成绩:
```c++
struct Record {
char name[20];
double score;
};
```
2. 打开二进制文件并检查是否成功打开:
```c++
ifstream infile("record.dat", ios::binary);
if (!infile) {
cout << "Failed to open file!" << endl;
return 0;
}
```
3. 读取文件中的记录并输出姓名和成绩:
```c++
Record rec;
while (infile.read((char*)&rec, sizeof(rec))) {
cout << "Name: " << rec.name << ", Score: " << rec.score << endl;
}
```
4. 关闭文件:
```c++
infile.close();
```
完整代码如下:
```c++
#include <iostream>
#include <fstream>
using namespace std;
struct Record {
char name[20];
double score;
};
int main() {
ifstream infile("record.dat", ios::binary);
if (!infile) {
cout << "Failed to open file!" << endl;
return 0;
}
Record rec;
while (infile.read((char*)&rec, sizeof(rec))) {
cout << "Name: " << rec.name << ", Score: " << rec.score << endl;
}
infile.close();
return 0;
}
```
阅读全文