C++中怎么使用read()读取结构体数组


在C++中,可以使用read()函数从文件中读取结构体数组。下面是一个示例代码:

#include <iostream>#include <fstream>using namespace std;struct Student {string name;int age;};int main() {int numStudents = 3;Student students[numStudents];ifstream infile("students.txt", ios::binary);if (!infile) {cerr << "Error opening file" << endl;return 1;}infile.read(reinterpret_cast<char*>(students), sizeof(Student)*numStudents);for (int i = 0; i < numStudents; i++) {cout << "Student " << i+1 << ": " << students[i].name << ", " << students[i].age << " years old" << endl;}infile.close();return 0;}

在此示例中,首先定义了一个包含学生姓名和年龄的结构体Student。然后在main函数中定义了一个包含3个学生的数组students。接着打开一个名为"students.txt"的二进制文件,并使用read()函数从文件中读取结构体数组。最后,遍历数组并输出每个学生的姓名和年龄。

注意:在使用read()函数时,需要将结构体数组强制转换为char*类型,以便与read()函数的参数匹配。


上一篇:c++中的read函数怎么使用

下一篇:Lua中怎么声明和赋值变量


c++
Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器