我已经创建了一个类 Flight ,其信息以另一种方法存储在名为 data.txt 的二进制文件中。保存记录工作正常,但现在我在读取我保存的记录时遇到问题。它正在显示所有记录,直到文件(eof)结束。但是当记录显示完成时,会弹出一个错误,提示 Program.exe 已停止工作。
void Flight::ViewFlight(){
HANDLE hConsole; //Console colors
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
fstream data;
Flight flight;
data.open("data.txt",ios::in | ios::binary);
if (data.fail())
{
SetConsoleTextAttribute(hConsole, 12);
cout<<"\n\nFlight data does not exist yet";
cout<<"\n\nYou are being redirected to the Main Menu in 3 seconds\n\n";
cout<<"3\n\n";
Sleep(1000);
cout<<"2\n\n";
Sleep(1000);
cout<<"1\n\n";
Sleep(1000);
cout<<"0\n\n";
SetConsoleTextAttribute(hConsole, 15);
}
else{
while(data.read((char*) &flight, sizeof(flight)))
{
if(!data.eof())
{
SetConsoleTextAttribute(hConsole, 10);
cout<<"\n\n----------- Record for "<<flight.flightid<<" -----------\n";
SetConsoleTextAttribute(hConsole, 15);
cout<<"\nFlight Number \t\t: "<<flight.flightnumber;
cout<<"\nDeparture Airport\t: "<<flight.departAirport;
cout<<"\nArrival Airport\t\t: "<<flight.arriveAirport;
cout<<"\nDeparture Time\t\t: "<<flight.departTime.hour<<":"<<flight.departTime.minute;
cout<<"\nDeparture Date\t\t: "<<flight.departDate.day<<"/"<<flight.departDate.month<<"/"<<flight.departDate.year;
cout<<"\nPrice \t\t\t: RM "<<flight.price;
cout<<"\nBusiness Class Seats\t: "<<flight.bseat;
cout<<"\nFirst Class Seats\t: "<<flight.fseat;
cout<<"\nEconomy Class Seats\t: "<<flight.totalseat;
cout<<endl;
}
}
}
data.close();
}