我正在学习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;
}