建立一个数组将实训12第2题定义的 学生数据存入数组。 数据为: { {"2020B200301","刘滨","男",18,{2020,9,20},70,85}, {"2020B200302","阚美娟","女",17,{2020,9,20},87,95}, {"2020B200303","胡大勇","男",17,{2020,9,20},69,80}, {"2020B200305","黎丽","女",18,{2020,9,20},68,88}, {"2020B200309","金鑫","男",19,{2019,9,1},90,85} } 将这些数据写人磁盘保存起来。
时间: 2023-08-27 11:21:38 浏览: 65
好的,以下是实现上述要求的C++代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct student {
string id; // 学号
string name; // 姓名
string gender; // 性别
int age; // 年龄
int birthday[3]; // 生日
int score1; // 成绩1
int score2; // 成绩2
};
int main() {
student stu[5] = {
{"2020B200301","刘滨","男",18,{2020,9,20},70,85},
{"2020B200302","阚美娟","女",17,{2020,9,20},87,95},
{"2020B200303","胡大勇","男",17,{2020,9,20},69,80},
{"2020B200305","黎丽","女",18,{2020,9,20},68,88},
{"2020B200309","金鑫","男",19,{2019,9,1},90,85}
};
ofstream outFile("students.txt"); // 打开输出文件流
if (outFile.is_open()) { // 如果成功打开文件
for (int i = 0; i < 5; i++) {
outFile << stu[i].id << " " << stu[i].name << " " << stu[i].gender << " " << stu[i].age << " ";
outFile << stu[i].birthday[0] << "-" << stu[i].birthday[1] << "-" << stu[i].birthday[2] << " ";
outFile << stu[i].score1 << " " << stu[i].score2 << endl;
}
outFile.close(); // 关闭文件
} else {
cout << "Unable to open file!" << endl;
}
return 0;
}
```
这段代码定义了一个名为`student`的结构体,包含了学生信息的各个字段。然后定义了一个长度为5的`stu`数组,将实训12第2题定义的学生数据存入其中。接着打开一个输出文件流,将学生数据写入磁盘文件`students.txt`中,最后关闭文件流。
阅读全文