I've written a simple piece of code using Turbo C++ which will save ID and balance of a bank costumer to a .dat file. But sometimes when I enter an id or balance (especially 3333 as id or 3333 as balance) and then display data, the
code does not work, and nothing happens.
Then on adding another account's data it gives random garbage values, and continues to give random garbage on adding new accounts. I need a little help to solve this problem.
Below is the code:
#include <constream.h>
#include <fstream.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
struct data
{
int id;
long bal;
char date[20];
data()
{
id=0;
bal=0;
}
}d1,d2;
void addaccount(void)
{
clrscr();
cout<<"\t\t\t Add New Account\n";
ofstream obj("d:\\tc\\data1.dat",ios::app);
cout<<"Enter ID ";
cin>>d1.id;
cout<<"\nEnter Amount Deposited at Account Opening ";
cin>>d1.bal;
while(d1.bal<2000)
{
cout<<"Amount should be Greater then RS 1999 \n\t\t\TEnter Amount Again ";
cin>>d1.bal;
}
{
time_t t;
struct tm * x;
time(&t);
x=localtime(&t);
strftime(d1.date,21,"\n%Y/%m/%d\n%H:%M:%S",x);
}
obj.write((char*)&d1,sizeof(data));
obj.close();
}
void dispall(void)
{
clrscr();
cout<<"\t\t\tAll Accounts \n\n\n";
ifstream obj1("d:\\numan\\data1.dat");
while(obj1.read((char*)&d1,sizeof(data))!=0)
{
cout<<"ID = "<<d1.id;
cout<<" Balance = "<<d1.bal<<endl<<endl;
}
obj1.close();
getch();
}
main()
{
clrscr();
int menu;
while(menu!=8)
{
clrscr();
cout<<"\t\t\tBANK MENU\n\t\t Enter Required key To perform a task \n";
cout<<"Press \n1=> Add New Account \n";
cout<<"2=> Display All Accounts \n";
/*cout<<"3=> Search An Account\n";
cout<<"4=> Delete An Account\n";
cout<<"5=> Delete All Accounts\n";
cout<<"6=> Updat An Account\n";
cout<<"7=> History of An Account\n";
*/
cout<<"8=> Exit\n";
cin>>menu;
switch(menu)
{
case 1:addaccount();
break;
case 2:dispall();
break;
/*case 3:search1(0);
break;
case 4:delet1(0);
break;
case 5:deletall();
break;
case 6:update1();
break;
case 7:search1(1);
break; */
case 8: break;
default:cout<<"Wrong Number Pressed";
getch();
}
}
return(0);
}