我要提前感谢任何人!我应该做的是从文件(“inventory.txt”)读取数据并将数据传递给对象矢量 . 所有数据都应该存储在一个矢量中,包括两个类信息,因此类车辆的公共部分中的类经销商的指针 . 这是txt文件中的数据;
2K458D345
Mitsubishi
Eclipse
2003
1,650.00
Rocky Mountain Dealership
Denver, Colorado
这是我的 class 定义:
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
最后这是我到目前为止编写的函数,carLot是Vehicle类型向量的名称 . 我还打算做的是创建一个临时对象来读取数据然后将其传递给一个新对象(导师推荐);
void readInv(vector<Vehicle>& carLot) {
Vehicle tempVehicle;
ifstream invFile;
invFile.open("inventory.txt");
cout << "the file is being read" << endl;
while( ! invFile.eof()){
}
}
我知道这有点长,但我很困难,无法弄清楚如何正确地将数据导入临时对象 . 如果有一个更容易的方式我打开它,但请,我将不胜感激任何帮助!非常感谢!
编辑我dident意味着矢量,当我第一次发布这个,我的意思是我想直接从文件中读取数据到临时对象 .
1 回答
您可以使用getline()一次将一行添加到字符串中,然后插入到矢量中 . 如果你有一个不同类型的格式化线,我建议使用sscanf . 例如:
我会更进一步,将库存升级到.ini文件,如下所示:
创建一个.ini文件阅读器,它将每行读入一个格式为:key = value的map <string,string> . 之后,您可以使用以下方法调用每个属性:
你也可以将我之前提到的sscanf方法应用于 Map .