【发布时间】:2011-07-03 21:02:48
【问题描述】:
我正在尝试将文本文件中的一些数据加载到结构向量中。我的问题是,你如何表示向量的大小?或者我应该使用矢量 push_back 函数动态地执行此操作,如果是,那么在填充结构时它是如何工作的?
完整的程序概述如下:
我的结构定义为
struct employee{
string name;
int id;
double salary;
};
文本文件 (data.txt) 包含以下格式的 11 个条目:
Mike Tuff
1005 57889.9
其中“Mike Tuff”是姓名,“1005”是 ID,“57889.9”是薪水。
我正在尝试使用以下代码将数据加载到结构向量中:
#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;
}
执行此操作时,我收到一条错误消息:“调试断言失败!表达式:向量下标超出范围。”
【问题讨论】: