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

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...