在c ++中使用向量时,无法从文件中读取类对象

时间:2018-05-24 08:03:07

标签: c++ visual-studio-2017

我正在学习C ++,我正在Visual Studio 2017社区中创建一个简单的C ++代码。当程序从文件中读取对象时,vs2017会抛出异常。所以如何解决这些问题。

    fstream File; Company Temp;  try{ vector<Company>Object; // Company class name

        cout << " 1. Show Data "; 
        cout << " 2. Put Data\n";
        cout << " => ";
        int a; cin >> a; cin.ignore(1000, '\n');
        if (a == 1)
            throw 5;
        Temp.Get_Data();
        Object.push_back(Temp);
        File.open("Ma.bin", ios::binary | ios::out | ios::app);
        int i = 0;
        for (vector<Company>::iterator It = Object.begin(); It != Object.end(); It++) {
            File.write((char *)&Object[i], sizeof(Object[i]));
            i++;
        }
        File.close();

    }


    catch (int) {
        Object.clear();
        File.open("Ma.bin", ios::binary | ios::in);
        File.seekg(0, ios::end);
        auto total = File.tellg() / sizeof(Company);
        cout << " total Object write " << total << "\n";
        cout << " Which One you want to Dispaly ?"; int Number; cin >> Number; cin.ignore(1000, '\n');
        int Position = (Number - 1) * sizeof(Company);
        File.seekg(Position);
        File.read((char *)&Temp, sizeof(Temp)); //this is the bug , if i comment this line then programme runs ok
        Object.push_back(Temp);
        File.close();
        vector<Company>::iterator It = Object.begin();
        It->Put_Data();
    }
    return 0;
}

this is the exception given by Vs2017 while reading objects from file

0 个答案:

没有答案