I tried to write a Program to store Info of Items in a Binary File. But except the 1st record, all other Records read thro' ShowFile() show only junk value. I have been trying to find the problem, but my code seems to be error-free to me. So, fellow Programmers help your newbie, find his Mistakes! (Note: I used Turbo C++ for compiling). Here is the code:
looks like a problem.
I suggest that line is deleted, it isn't matched by any corresponding file input in the ShowFile() function, which would explain why things get out of sync after the first record.
void ShowFile()
{
clrscr();
store s;
ifstream f1;
f1.open("stores.dat", ios::binary);
cout<<"\n\nShowing Contents of the File";
while(f1)
{
s.LoadFromStream(f1);
s.Details();
}
f1.close(); // not needed
}
void NewFile()
{
store s;
ofstream f1;
f1.open("stores.dat",ios::binary);
char ch;
cout<<"\n\nFresh file \"stores.dat\" created! Any previous content of any file of the SAME NAME is deleted!";
do
{
s.NewItem();
s.SaveToStream(f1);
cout<<"Do you want to Add more Items > (y/n):\t";
cin>>ch;
}while (ch=='y');
cout<<"All Entries have been Stored in the File successfully!";
f1.close(); // not needed
}
Oh Yeah! Thanks Thomas1965. The code is finally working!
But Only one Problem.
Using while(f1) reads the last file two times. And using while(s.LoadFromStream(f1)) also seems to be an error!
So, Is there another way to counter the problem!
If it works then there is nothing to fix.
A common problem with cin is that '\n' remains in the input buffer and the next input is skipped.
Normally you use cin.ignore (255, '\n'); to remove the '\n' from the input buffer.