在c++中,我写了一个简单的程序,它接受4到6条记录,然后当airline_no相同时不再接受,即1?源码是:
#include<fstream.h>
#include<conio.h>
#include<dos.h>
#include<string.h>
#include<stdlib.h>
#include<process.h>
#include<stdio.h>
int lno;
struct airln {int airline_no,routeno,dep_time,arr_time;
char port_d[15],port_a[15],week_day[10]; }r2;
class route
{
public:
void getroute()
{
cout<<"\n\tRoute no.: ";
cin>>r2.routeno;cout<<"\n";
cout<<"\tDay of Departure: ";
gets(r2.week_day);cout<<"\n";
cout<<"\tAirport for departure: ";
gets(r2.port_d);cout<<"\t";
cout<<"Departure Time: ";
cin>>r2.dep_time;cout<<"\n";
cout<<"\tAirport for arrival: ";
gets(r2.port_a);cout<<"\t";
cout<<"Arrival Time: ";
cin>>r2.arr_time;cout<<"\n";
cout<<"\n\tAirline no.: ";
cin>>r2.airline_no;
}
void display_route()
{
cout<<"\n Route No : ";cout<<r2.routeno;
cout<<"\n ";
cout<<r2.port_d;cout<<"\t";
cout<<r2.dep_time;cout<<"\t\t";
cout<<r2.port_a;cout<<" \t";
cout<<r2.arr_time;cout<<"\t\t";
cout<<r2.week_day;cout<<"\n";
}
}r3;
void main()
{
clrscr();
int airlnno,rtnodel,cntr;
char airlinename[30];
ifstream fin,fin1;
ofstream fout;
do
{
cout<<"\t1. Insert Data.\n";
cout<<"\t2. View Data.\n";
cout<<"\t3. Exit.\n";
cout>>"\tEnter Choice : ";cin>>cntr;
switch(cntr)
{
case 1:r3.getroute();
fout.open("testdata.dat",ios::app);
if(!fout)
{
gotoxy(25,10);
cout<<"No file exists or file can\'t be opened\n";
gotoxy(25,22);
cout<<"Please Press Any Key to Continue.......";
getch();
clrscr();
}
fout.write((char *) &r2,sizeof(r2));
fout.close();
clrscr();
break;
case 2:fin.open("testdata.dat",ios::in);
if(!fin)
{
gotoxy(25,20);
cout<<"No file exists or file can\'t be opened\n";
gotoxy(25,22);
cout<<"Please Press Any Key to Continue.......";
getch();
clrscr();
break;
}
cout<<"\n Dep-Airport\t";
cout<<"Dep-Time\t";
cout<<"Arr-Airport\t";
cout<<"Arr-Time\t";
cout<<"Week Day\n";
fin.read((char *) &r2,sizeof(r2));
while(!fin.eof())
{
r3.display_route();
fin.read((char *) &r2,sizeof(r2));
}
fin.close();
gotoxy(25,22);
cout<<"Please Press Any Key to Continue.......";
getch();
clrscr();
}
} while(!(cntr==3));
}发布于 2010-08-24 20:26:38
你必须为此使用文件吗?您可以始终使用std::map,并将airline_no作为关键字。
我也避免使用全局结构和类。
编辑: k,我遇到了一个问题,发现1050是问题所在。我可以将它移到更早的记录,它也会停在那里。我认为问题在于1050以某种方式触发了文件的结束。尝试使用以下替换行打开二进制文件:
fout.open("testdata.dat",ios::app | ios::binary);
fin.open("testdata.dat",ios::in | ios::binary);而不是:
fout.open("testdata.dat",ios::app);
fin.open("testdata.dat",ios::in);编辑:刚刚进行了检查,1050转换为041A,转换为字符传输结束,然后....SUB或EOF。我认为这就是你的问题,在二进制模式下,这应该不再是问题。
发布于 2010-08-24 20:50:32
每次收到输入后,都需要清除cin。可能是在do while循环的开始。cntr值可以从先前输入的值中获取。如果恰好是3,它将退出while循环,并且不接受任何进一步的记录。
尝试在do while循环开始时使用cin.clear()或cin.ignore()函数。
https://stackoverflow.com/questions/3556301
复制相似问题