首页 > 解决方案 > 如何从文件读取特定数量的字符到结构

问题描述

我需要从这个数据文件中读取 20 个字符:

    7
    Petras A. Petraitis 120 15 20 0 
    Jurgis Jurgutis     222 16 12 22
    Rimas Jonas         138 15 15 59
    Bei Lin Sin Mun     23 15 0 0   
    Zigmas Nosis        256 16 23 9 
    Romas Senasis       111 15 15 15
    Jurgis Stasys Lydeka199 16 13 9 
    6
    256 16 43 15
    120 15 50 10
    111 16 5 35 
    199 16 35 59
    222 16 42 22
    23 15 30 0  

基本上每个字母和空格直到数字。我曾尝试使用 read(),但我无法让它与 struct 一起使用。我也一直在尝试使用 getline(),但它对我也不起作用。我一直在到处寻找,但大多数教程都显示直接用户输入,而不是从文件中读取。

    #include <iostream>
    #include <fstream>
    #include <string>

    using namespace std;

    struct competition{
        string name; // athletes name
        int athleteNum; // number
        int startHours; // starting time: hours
        int startMin; // starting time: minutes
        int startSec; // starting time: seconds
    };

    int main()
    {
        ifstream duom ("U2.txt");

        competition athletes[30];
        int n; // amount of athletes
        duom >> n;
        for (int i=0; i<n; i++){
            duom.getline(athletes[i].name, 20);
        }
        return 0;
    }

使用 getline() 代码无法编译,所以我可能语法错误并且 read() 似乎不适用于 struct。

标签: c++

解决方案


正如 alezh 指出的那样,istream::getline()需要 a char*not a std::string。您可以创建一个char hold[50]变量传递给istream::getline(): duom.getline(hold, 50);,然后将您的分配std::string给那个 : athletes[i].name = std::string(hold, 20);

也正如他指出的那样,duom >> n;不会让你进入下一行。您可能希望duom.ignore(20, '\n')在该行之后从正确的行开始。或者首先不使用>>with getline

嵌套for循环有什么用?您可以摆脱第二for行。


推荐阅读