C++:如何从文件读取到对象向量

In C++: How to read from file into a vector of objects

本文关键字:读取 对象 向量 文件 C++      更新时间:2023-10-16

我想从用户指定的文件名中读取数据到对象向量中。我想读懂的每个向量元素有五个不同的成员变量。在文件中,将有多个条目(由五个成员变量组成的组)读入每个向量元素。这是我到目前为止的(不完整)代码:

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);
}