2011-02-24 67 views
3

我想从文本文件加载一些数据到结构向量中。我的问题是,你如何指示矢量的大小?或者我应该使用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; 
} 

当我执行,我得到一个错误,指出:“调试断言失败表达式:矢量标出来范围“。

回答

2

vector是可膨胀的,但只能通过push_back()resize()和一些其他的功能 - 如果使用emps[i]i大于或等于所述vector的大小(其最初是0),则程序会崩溃(如果你幸运的话)或产生奇怪的结果。如果您事先知道所需的尺寸,可以打电话给emps.resize(11)或声明它为vector<employee> emps(11);。否则,您应该在循环中创建一个临时employee,读入并将其传递到emps.push_back()

+0

哦,我的天啊,你是天使!得到它与以下新的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

+0

您还可以使用'insert'将结构放置到指定位置,而'push_back'则总是附加到该向量的末尾。 – AJG85 2011-02-24 21:44:56

+0

@ user633055:很高兴听到它;你在这里展示的代码就是我的想法。如果您满意,您应该将您的首选答案标记为已接受;这将使您更有可能回答您将来的问题。 :-) – 2011-02-25 00:20:50

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

不错的想法,但原始代码使用了'ifstream',而不是'cin'。 – aschepler 2011-02-24 21:36:16

+2

你在开玩笑吧? – 2011-02-24 23:38:43