我想從文本文件加載一些數據到結構向量中。我的問題是,你如何指示矢量的大小?或者我應該使用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