Search code examples
c++vectorstructifstream

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


I tried to read a file called "qbdata.txt" and save the data in a vector called quarterbacks. So, I created this struct 'Record' to save different types of variables in the file and 'quarterbacks' is supposed to be a vector of struct. Here is my code. However, it didn't work out. When I test the size of my vector, it resulted zero. Can you tell me what's wrong with my code? (I also uploaded a piece of the text file I am trying to withdraw data from)

#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();
}

Solution

  • Read one line at a time using std::getline, then use std::stringstream to parse the data. Example:

    #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";
        }
    }