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"
using namespace std;
vector<employee>emps;
void loadData(string filename)
{
int i = 0;
ifstream fileIn;
fileIn.open(filename.c_str());
if( ! fileIn )
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.
source
share