2011-02-24 133 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

相關問題