如何读取文件中的数据并创建结构向量?

How to read data in a file and create a vector of struct?

我尝试读取一个名为 "qbdata.txt" 的文件并将数据保存在一个名为 quarterbacks 的向量中。所以,我创建了这个结构 'Record' 来在文件中保存不同类型的变量,而 'quarterbacks' 应该是一个结构向量。这是我的代码。但是,它没有成功。当我测试向量的大小时,结果为零。你能告诉我我的代码有什么问题吗? (我还上传了一段我试图从中提取数据的文本文件)

#include <iostream>
#include <fstream>
#include <stdexcept>
#include <vector>

struct Record{
    int year;
    string name;
    string team;
    int completions, attempts, yards, touchdowns, interceptions;
    double rating;
};

void readFile()
{
    ifstream infile;
    Vector<Record> quarterbacks;

    infile.open("qbdata.txt");
    if (infile.fail()){
        throw runtime_error ("file cannot be found");
    }
    while (!infile.eof()){
        Record player;
        if (infile >> player.year >> player.name >> player.completions >> player.attempts >>
            player.yards >> player.touchdowns >> player.interceptions)
            quarterbacks.push_back(player);
        else{
            infile.clear();
            infile.ignore(100, '\n');
        }
    }
    infile.close();
}

可能是由于不满足条件而未填充矢量。运算符 >> 一次取一个词并忽略空格,例如,如果您读取的内容多于文件中的内容,则不满足条件。

使用std::getline一次读取一行,然后使用std::stringstream解析数据。示例:

#include <sstream>
...
string line;
while(getline(infile, line))
{
    cout << "test... " << line << "\n";
    stringstream ss(line);
    Record player;
    if(ss >> player.year >> player.name >> player.completions >> player.attempts >>
        player.yards >> player.touchdowns >> player.interceptions)
    {
        quarterbacks.push_back(player);
        cout << "test...\n";
    }
}