我想从文本文件加载一些数据到结构向量中。我的问题是,你如何指示矢量的大小?或者我应该使用vector_back_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;
}
当我执行,我得到一个错误,指出:“调试断言失败表达式:矢量标出来范围“。
哦,我的天啊,你是天使!得到它与以下新的while循环完美合作:\t'while(fileIn) \t { \t \t employee temp; \t \t getline(fileIn,temp.name); \t \t fileIn >> temp.id; \t \t fileIn >> temp.salary; \t \t fileIn.ignore(1); \t \t emps.push_back(temp); \t \t i ++; \t}' – 2011-02-24 21:11:31
您还可以使用'insert'将结构放置到指定位置,而'push_back'则总是附加到该向量的末尾。 – AJG85 2011-02-24 21:44:56
@ user633055:很高兴听到它;你在这里展示的代码就是我的想法。如果您满意,您应该将您的首选答案标记为已接受;这将使您更有可能回答您将来的问题。 :-) – 2011-02-25 00:20:50