【问题标题】:To store values in Array or vector of Objects reading from file c++98将值存储在从文件 c++98 读取的对象的数组或向量中
【发布时间】:2021-06-19 23:07:19
【问题描述】:

文件中有 6 列条目,每列分别指定(天、小时、温度、相对湿度、风速、全球水平太阳辐射)的值。我们如何将这些值存储在对象的数组或向量中?请帮忙

1   1   13.7    58  2.7 0
1   2   13.5    64  1.4 0
1   3   13  70  0   0
1   4   12.2    75  0.5 0
1   5   11.4    80  1   0
1   6   10.6    85  1.5 0
1   7   11.1    80  1   0
1   8   11.5    78  0.5 13
1   9   12  76  0   150
1   10  15.1    76  1   355
1   11  18.3    73  2.1 532
1   12  21.4    70  3.1 652
1   13  21.9    62  2.9 706
1   14  22.5    56  2.8 686
1   15  23  49  2.6 593
1   16  22.6    50  2.4 434
1   17  22.2    52  2.3 234
1   18  21.8    53  2.1 45
1   19  19.9    57  1.4 0
1   20  17.9    60  0.7 0
1   21  16  63  0   0
1   22  15.7    60  1.2 0
1   23  15.5    56  2.4 0
1   24  15.2    53  3.6 0

2   1   14.1    58  2.4 0
2   2   13.1    63  1.2 0
2   3   12  69  0   0
2   4   11.1    74  0   0
2   5   10.1    79  0   0
2   6   9.2 84  0   0
2   7   9.9 79  0.3 0
2   8   10.7    75  0.7 13
2   9   11.4    71  1   150
2   10  13.5    60  1.3 358
2   11  15.6    51  1.7 539
2   12  17.7    43  2.1 664
2   13  19.8    37  2.4 718
2   14  21.9    31  2.7 697
2   15  24  26  3.1 603
2   16  23.7    27  2.8 443
2   17  23.3    28  2.4 240
2   18  23  29  2.1 47
2   19  21.1    35  1.9 0
2   20  19.1    42  1.7 0
2   21  17.2    50  1.5 0
2   22  16.1    53  1.5 0
2   23  15.1    57  1.5 0
2   24  14  61  1.5 0

【问题讨论】:

    标签: c++ arrays file vector c++98


    【解决方案1】:

    std::getline 提取每一行,std::stringstream 从这一行提取每个值:

    #include <iostream>
    #include <string>
    #include <fstream>
    #include <sstream>
    #include <vector>
    
    struct Data {
        unsigned int days, hours;
        float humidity, windSpeed, radiation;
    };
    
    int main()
    {
        std::vector<Data> data;
    
        std::ifstream file("yourfile.txt");
        for (std::string line; std::getline(file, line); )
        {
            Data d;
            std::stringstream ss(line);
            ss >> d.days >> d.hours >> d.humidity >> d.windSpeed >> d.radiation;
            data.push_back(d);
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多