当前位置:首页 C++ > 正文

c++怎么从一个文件中读数据到结构体中

作者:野牛程序员:2023-05-30 10:25:58 C++阅读 3073

在C++中,你可以使用文件输入流(ifstream)和结构体来从文件中读取数据。以下是一个简单的示例:

#include <iostream>
#include <fstream>

using namespace std;

struct Student {
    string name;
    int age;
    double gpa;
};

int main() {
    ifstream file("students.txt");  // 打开文件

    if (!file) {
        cout << "无法打开文件!" << endl;
        return 1;
    }

    Student student;

    while (file >> student.name >> student.age >> student.gpa) {
        // 读取文件中的数据,并将其存储到结构体对象中
        cout << "姓名: " << student.name << endl;
        cout << "年龄: " << student.age << endl;
        cout << "GPA: " << student.gpa << endl;
        cout << endl;
    }

    file.close();  // 关闭文件

    return 0;
}

在上述示例中,我们首先打开了一个名为"students.txt"的文件,并将其与输入文件流(ifstream)对象绑定。接下来,我们使用一个while循环来从文件中读取数据,并将其存储到一个名为"student"的结构体对象中。每次循环迭代时,我们将打印出读取的数据。最后,我们关闭文件。

假设"students.txt"的内容如下:

John 20 3.8
Emily 19 3.7
Michael 21 3.9

运行上述代码将输出:

姓名: John
年龄: 20
GPA: 3.8

姓名: Emily
年龄: 19
GPA: 3.7

姓名: Michael
年龄: 21
GPA: 3.9

这样,你就可以成功地从文件中读取数据到结构体中了。请注意,上述示例假设文件中的数据与结构体的成员类型相匹配,并且每行数据的格式是空格分隔的。你可以根据你的文件格式和结构体定义进行适当的修改。

野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击