C++:如何从文件读取到对象向量
In C++: How to read from file into a vector of objects
我想从用户指定的文件名中读取数据到对象向量中。我想读懂的每个向量元素有五个不同的成员变量。在文件中,将有多个条目(由五个成员变量组成的组)读入每个向量元素。这是我到目前为止的(不完整)代码:
while (!inputFile.eof())
{
for (unsigned int count = 0; inputFile.eof(); count++)
{
cout << "Vehicle #" << (count + 1) << endl;
inputFile >> temp[count].setVIN();
cout << "VIN: " << temp[count].getVIN() << endl;
inputFile >> temp[count].setMake() << endl;
cout << "Make: " << temp[count].getMake() << endl;
inputFile >> temp[count].setModel() << endl;
cout << "Model: " << temp[count].getModel() << endl;
inputFile >> temp[count].setYear() << endl;
cout << "Year: " << temp[count].getYear() << endl;
inputFile >> temp[count].setPrice() << endl;
cout << "Price: " << temp[count].getPrice() << endl
<< endl;
}
}
但是,此代码已经存在几个问题。其中之一是setVIN()
、setMake()
、setModel()
、setYear()
和setPrice
成员函数需要一个参数(用于设置 VIN、Make、Model 等的值)。下面是类声明:
class Vehicle
{
private:
string VIN;
string make;
string model;
int year;
double price;
public:
Vehicle(string, string, string, int, double);
Vehicle();
string getVIN();
string getMake();
string getModel();
int getYear();
double getPrice();
void setVIN(string);
void setMake(string);
void setModel(string);
void setYear(int);
void setPrice(double);
};
最后,给定我发布的第一个代码块,在inputFile >> .....
错误消息的行上指出"没有操作数'>>'匹配这些操作数操作数操作数类型是 std::ifstream>> void"
有人能帮我度过这个路障吗?
谢谢!
首先,
这段代码很糟糕。
inputFile >> temp[count].getVIN();
它从getVIN()
获取一个字符串,然后尝试读取临时字符串。 相反,您需要使用类似以下内容的内容:
string vin;
inputFile >> vin;
temp[count].setVin(vin);
其次,创建一个读取整个对象的operator>>
更具意识形态,以便您的循环可以更干净。
istream& operator>>(istream& is, Vehicle & v) {
string vin;
inputFile >> vin;
v.setVin(vin);
...
}
如果你把它作为一个成员函数,你可以改为写
// You probably want to add error checking to each read too
void Vehicle::readFromStream(istream & is) {
is>>vin;
is>>make;
...
}
istream& operator>>(istream& is, Vehicle & v) {
v.readFromStream(is);
return is;
}
那么你的循环将变成
Vechicle v;
while(input>>v) {
std::cout<<v<<std::endl;
}
只要你也添加一个明智的operator<<
(以同样的方式)。
如果您真的想将它们存储在列表中,那么:
std::vector<Vehicle> vehicles;
Vehicle v;
while(input>>v) {
vehicles.push_back(v);
}
相关文章:
- 如何在 C++ 中使用提升属性树从 JSON 文件中读取对象数组
- 从文本文件中读取对象
- 通过自定义分隔符从文件中读取对象数组
- 在文件中写入和读取对象
- 在多线程中是否可能发生读取对象的一半大小?
- C 从文件中读取对象具有数组属性
- 从常量读取对象 unordered_map
- 从文件读取对象并获取错误
- 正在从二进制文件中读取对象列表
- 从文件中写入/读取对象
- 从文件 c++ 读取对象
- 如何从 TMXObjectGroup 读取对象定制属性
- C++:编译器无法读取对象数组
- 直接读取对象
- 试图读取对象向量时程序崩溃
- 从文件中读取对象并打印
- C++流写入/读取对象
- c++中使用fstream读取对象
- 从c++文件中读取对象
- 从文件中读取对象时未定义的符号