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

   2024-10-22 8940
核心提示:在C++中,可以使用read()函数从文件中读取结构体数组。下面是一个示例代码:#include iostream#include fstreamusing namespace

在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()函数的参数匹配。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号