想写一个飞机管理系统读取数据时发生了错误,但不知道哪里错了,有没有神帮忙看一看,当我第一次写入时貌似没有写入,当我写入完成后,将几个飞机注释了也不能重新读出来。能看看是哪里有错误吗?
用代码块功能插入代码,请勿粘贴截图
#include <iostream>
#include <string.h>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
#include <set>
using namespace std;
string getcompany(char no[10])//通过前两个字母找公司
{
string company(no);
company = company.substr(0,2);
if(company == "CA") return "中国国际航空公司";
if(company == "CZ") return "中国南方航空公司";
if(company == "MU") return "中国东方航空公司";
else return "unkowned";
}
class Flight//航班模块
{
public:
char no[10];
char startplace[10];
char endpalce[10];
char schedule[10];
char starttime[10];
char endtime[10];
char airtype[10];
double price;
string company;
Flight(){}
Flight(char uno[],char ustartplace[], char uendplace[],char uschedule[],char ustarttime[], char uendtime[],char uairtype[], double uprice)
{
strcpy(no,uno);
strcpy(startplace,ustartplace);
strcpy(endpalce,uendplace);
strcpy(schedule,uschedule);
strcpy(starttime,ustarttime);
strcpy(endtime, uendtime);
strcpy(airtype,uairtype);
price = uprice;
company = getcompany(no);
}
void input_information();
bool operator < (const Flight &f) const{
return strcmp(f.no,this->no) > 0;
}
bool operator > (const Flight &f) const{
return strcmp(f.no,this->no) < 0;
}
};
int main()
{
fstream flightinformation("flightinformation.dat", ios::out|ios::binary);//
set<Flight> flight;
Flight flight6;
Flight newflight;
set<Flight>::iterator it;
int n = 0;
flightinformation.open("flightinformation.dat",ios::in|ios::binary);
if(!flightinformation)
{
cout << "文件打开失败" << endl;
}
while(flightinformation)
{
flightinformation.read((char*)&flight6, sizeof(flight6));
int cc = flightinformation.gcount(); // *** 新添加,判断读字节数是否吻合
if(cc == sizeof(Flight))
{
cout << flight6.price << endl;
cout << flight6.no << " " << flight6.startplace << endl;
flight.insert(flight6);
}
}
flightinformation.close();
Flight flight1("CA2386","珠海","上海","12367","15:25","15:25","波音737-8",680);
Flight flight2("CA9988","北京","香港","1234567","19:00","22:00","南飞C919",1600);
Flight flight3("CZ5685","杭州","重庆","357","18:30","20:35","空客380",568);
Flight flight4("MU9816","广州","北京","1234567","10:50","13:16","波音787",780);
Flight flight5("MU9912","新加坡","旧金山","157","12:00","23:30","波音737-8",8768);
flight.insert(flight1);
flight.insert(flight2);
flight.insert(flight3);
flight.insert(flight4);
flight.insert(flight5);
//showmain(flight,flightinformation);
flightinformation.open("flightinformation.dat", ios::out|ios::binary);
for(it = flight.begin(); it != flight.end(); it++)//定义前向迭代器遍历输出
{
flightinformation.write((char*)& (*it), sizeof(Flight));
}
flightinformation.close();
return 0;
我的解答思路和尝试过的方法
我希望能先从几个定义的航班中读取数据,然后生成了二进制文件,接着将航班注释掉,我仍能从文件中读取到之前的航班。