温馨提示×

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

c++
小亿
85
2024-04-15 16:03:06
栏目: 编程语言

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

0