Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

c++ - Loading data into a vector of structures

I am trying to load some data from a text file into a vector of structures. My question is, how do you indicate the size of the vector? Or should I be using a the vector push_back function to do this dynamically, and if so, how does this work when populating a structure?

The full program is outlined below:

My structure is defined as

struct employee{
    string name;
    int id;
    double salary;
};

and the text file (data.txt) contains 11 entries in the following format:

Mike Tuff
1005 57889.9

where "Mike Tuff" is the name, "1005" is the id, and "57889.9" is the salary.

I am trying to load the data into a vector of structs using the following code:

#include "Employee.h" //employee structure defined in header file

using namespace std;

vector<employee>emps; //global vector 

// load data into a global vector of employees.
void loadData(string filename)
{
    int i = 0;
    ifstream fileIn;
    fileIn.open(filename.c_str());

    if( ! fileIn )  // if the bool value of fileIn is false
         cout << "The input file did not open.";

    while(fileIn)
    {
        fileIn >> emps[i].name >>emps[i].id >> emps[i].salary ;
        i++;
    }

    return;
}

When I execute this, I get an error that says: "Debug Assertion Failed! Expression: vector subscript out of range."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
std::istream & operator >> operator(std::istream & in, employee & e)
{
  return in >> e.name >> e.id >> e.salary; // double not make good monetary datatype.
}

int main()
{
  std::vector<employee> emp;
  std::copy(std::istream_iterator<employee>(std::cin), std::istream_iterator<employee>(), std::back_inserter(emp));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...