简体   繁体   中英

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

probably, the vector is not populated since condition is not met. the operator >> takes one word at time and ignores spaces, if you read more than in the file for example, the condition is not met.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM