Abhishek Ranjan Abhishek Ranjan - 3 days ago 4
C++ Question

strcpy is copying sth character onwards i string . How to resolve this error?

My complete code is at http://pastebin.com/ZTkn001r
There is a train database , and user enters train number to book a ticket.The function updt_tick should copy the values of train's name,source and destination into passenger's reservation object.But the problem is that 5th character onwards are only being copied. updt_tick function is at line 87. Here is the function's code sample.Train databse is entered by user.I am using codeblocks if it matters.

void updt_tick()
{
fstream f;
f.open("train.dat",ios::in | ios::binary);
while(f.read((char*)&t,sizeof(t)))
{
if (tno==t.tno)
{
strcpy(bp,t.source);
strcpy(dest,t.dest);
strcpy(tname,t.tname);
amt=SeatNum*t.PerSeatFare;
break;
}
}
f.close();
}


The train class is ->

class train
{
public:
int tno;
char tname[100];
char source[100];
char dest[100];
int PerSeatFare;

public:
void getdetail()
{
cout<<"Enter the details as follows\n";
cout<<"Train no:";
cin>>tno;
cin.ignore();
cout<<"Train name:";
gets(tname);
cout<<"Train Source Station:";
gets(source);
cout<<"Tarin Destination Station:";
gets(dest);
cout<<"Fare per seat in train :";
cin>>PerSeatFare;
}
void showdetail()
{
cout<<tno<<"\t"<<tname<<"\t"<<source<<"\t"<<dest<<"\t";
cout<<PerSeatFare;
}
}t;


The reserv class is ->
`

class reserv //Assume that cust select train according to his source and destination.
{

public:
int pnr;
int tno;
char tname[100];
char pnames[10][100];
int ages[10];
int SeatNum;
int i;
int d,m,y;
float amt;
char bp[100],dest[100];
void updt_tick()
{
fstream f;
f.open("train.dat",ios::in | ios::binary);
while(f.read((char*)&t,sizeof(t)))
{
if (tno==t.tno)
{
strcpy(bp,t.source);
strcpy(dest,t.dest);
strcpy(tname,t.tname);
amt=SeatNum*t.PerSeatFare;
break;
}
}
f.close();
}

public:
void getresdet()
{
cout<<"Enter the details as follows\n";
cout<<"Train no:";
cin>>tno;
cout<<"No of seats required:";
cin>>SeatNum;
cin.ignore();
for(i=0; i<SeatNum ; i++)
{
cout<<"Passenger name:";
gets(pnames[i]);
cout<<"Passenger age:";
cin>>ages[i];
cin.ignore();
}
cout<<"Date of travel:";
cin>>d>>m>>y;
cout<<"Details Accepted\n";
pnr=rand();
updt_tick();
}
void showresdet()
{
cout<<"Pnr no:"<<pnr;
cout<<"\nTrain no:"<<tno;
cout<<"\nTrain name:";
puts(tname);
cout<<"Boarding point:";
puts(bp);
cout<<"Destination pt:";
puts(dest);
cout<<"No of seats reserved:"<<SeatNum;
for(i=0; i<SeatNum; i++)
{
cout<<"Passenger name:";
puts(pnames[i]);
cout<<"Passenger age:"<<ages[i];
}
cout<<"\nDate of reservation:"<<d<<"-"<<m<<"-"<<y;
cout<<"\nYou must pay:"<<amt<<endl;
}
int getpnr()
{
return pnr;
}
};

Answer

Im not sure how did you manage to read 5 characters, because there is a problem is in your code. The file which you use to store train details is "trainS.dat", not "train.dat".

Comments