我使用 Turbo C++ 编写了一段简单的代码,它将银行客户的 ID 和余额保存到.dat
文件中。但有时当我输入一个id或balance (特别是3333作为id或3333作为balance)然后显示数据时,代码不起作用,什么也没有发生。
然后在添加另一个账户的数据时,它会给出随机垃圾值,并在添加新账户时继续给出随机垃圾。我需要一点帮助来解决这个问题。
下面是代码:
#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);
}