我要提前感谢任何人!我应该做的是从文件中读取数据(" 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
最后这是我到目前为止编写的函数,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()){
}
}
我知道这有点长,但我很困难,无法弄清楚如何正确地将数据导入临时对象。如果有一个更容易的方式我打开它,但请,我将不胜感激任何帮助!非常感谢你!
编辑当我第一次发布这个时,我意味着向量,我的意思是我想直接从文件中读取数据到临时对象。
答案 0 :(得分: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文件阅读器,将每行读入地图&lt; string,string&gt;格式为:key = value。 之后,您可以使用以下方法调用每个属性:
davidVehicle.setModel(map["model"]);
你也可以将我前面提到的sscanf方法应用于地图。