2017-05-03 98 views
0

我想先感謝任何人和大家!我應該做的就是從文件中讀取數據(「inventory.txt」),並將這些數據傳遞給對象向量。所有的數據應該存儲在一個單獨的向量中,包括兩個類別信息,因此是班級車輛公共部分的班級經銷商的指針。這是txt文件中的數據;如何從文件讀取數據到對象

2K458D345 
Mitsubishi 
Eclipse 
2003 
1,650.00 
Rocky Mountain Dealership 
Denver, Colorado 

這是我的類定義:

class Dealer{     //deceleration of class Dealer 

private:      //private variables 
string DealerName; 
string DealerAddress; 

public:       //public members 
          //class mutators 
void setName(string); 

void setAddress(string); 
          //class accessors 
string getName(); 

string getAddress(); 

Dealer();     // default constructor 

Dealer(string, string);  //overloaded constructor 
}; 

class Vehicle{     //decleration of class vehicle 

private:      //private member variables 
string VIN; 
string Make; 
string Model; 
int Year; 
double Price; 

public:       // public member variables and functions 
Dealer *Dealerprt;   //dealer class pointer 

Vehicle();     //default constructor 

Vehicle(string, string, string, int, double);  //overloaded constructor 
          //class mutators 
void setVIN(string);        //sets member variable VIN to value in v 

void setMake(string);        //sets member variable Make to value in m 

void setModel(string);        //sets member variable Model to value in M 

void setYear(int);         //sets member variable Year to value in y 

void setPrice(double);        //sets member variable Price to value in p 
//class accessors 
string getVin();         //returns value stored in member variable VIN 

string getMake();         //returns value stored in member variable Make 

string getModel();         //returns value stored in member variable Model 

int getYear();          //returns value stored in member variable Year 

double getPrice();         //returns value stored in member variable Price 

終於這是迄今爲止我已經寫的功能,並且是卡洛特型車輛的矢量的名字。另外我打算做的是創建一個臨時對象來讀取數據,然後將其傳遞給一個新的對象(導師的建議);

void readInv(vector<Vehicle>& carLot) { 

Vehicle tempVehicle; 

ifstream invFile; 
invFile.open("inventory.txt"); 
cout << "the file is being read" << endl; 

while(! invFile.eof()){ 



} 


} 

我知道這是有點長,但IM卡住,無法弄清楚如何正確地獲取數據到臨時對象。如果有一個更簡單的方式我打開它,但請我感謝任何幫助!非常感謝!

編輯我意味着矢量當我第一次發佈這個,我的意思是,我想直接從文件中讀入數據到臨時對象。

+0

這可能是SO上最常見的問題之一。見例如。下面列出的問題之一----> – user463035818

+0

下面是一條線索:std :: getline(invFile,line) – sithereal

+0

[使用getline()從文本文件讀入行並將\ _back插入到矢量對象](http://stackoverflow.com/questions/22390500/using-getline-to-read-in-lines-from-a-text-file-and-push-back-into-a-vector-of ) – cbuchart

回答

0

您可以使用getline()一次獲取一行到一個字符串中,然後插入到一個向量中。 如果你有一個不同類型的格式化線,我建議使用sscanf。例如:

sscanf(line.c_str(), "%f %f", &price, &size); 

我把它一步,升級庫存到.ini文件,如下所示:

[david_car] 
id = 2K458D345 
brand = Mitsubishi 
model = Eclipse 
year = 2003 
price = 1,650.00 
dealer = Rocky Mountain Dealership 
location = Denver, Colorado 

創建一個.ini文件閱讀器將讀取每行到地圖< string,string>格式:key = value。 後,你將可以通過調用每個屬性:

davidVehicle.setModel(map["model"]); 

,你也可以申請我先前與地圖中提到的sscanf的方法。