Loading data into a structure vector

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

The full program is described 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 identifier, and "57889.9" is the salary.

I am trying to load data into a structs vector 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 do this, I get the error message: "Debugging error." Expression: vector index out of range.

+3
source share
2

A vector , push_back(), resize() - emps[i] i, vector ( 0), ( ) . , , . emps.resize(11) vector<employee> emps(11);. employee , emps.push_back().

+2
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));
}
+4

Source: https://habr.com/ru/post/1794556/


All Articles