以下代码读取 3 个 obj 并将它们写入文件。但是我无法使用下面的代码正确检索对象。数据重复且无序
请帮助
旧代码:
#include<fstream.h>
#include<conio.h>
class mail
{
public:
char un[25]; // user name
char pd[25]; // passsword
void reg(int);
} obj[5];
void mail::reg(int k)
{
int i;
i=k;
clrscr();
cout<<"Enter user name ( enter unique name )\n";
cin>>un;
cout<<"Enter password\n";
cin>>pd;
ofstream filout;
filout.open("email",ios::app||ios::binary);
if(!filout)
{
cout<<"cannot open file\n";
}
else
{
cout<<"\n "<<i;
filout.write((char *)&obj[i],sizeof(mail));
filout.close();
}
cout<<"You are now registered. \n";
getch();
} // end of sign up or register func
void main()
{
int t;
clrscr();
obj[0].reg(0);
obj[1].reg(1);
obj[2].reg(2);
mail obj2;
ifstream filein;
filein.open("email",ios::in||ios::binary);
if(!filein)
{
cout<<"Unable to open file to read\n";
}
else
{
while(!filein.eof())
{
filein.read((char *)&obj2,sizeof(obj2));
cout<<"username "<<obj2.un<<" passwword "<<obj2.pd<<"\n";
}
filein.close();
}
getch();
}
另外请告诉我如何将代码放入stackoverflow。复制粘贴后手动放4个空格很累
更改后的新代码:
#include<fstream.h>
#include<conio.h>
struct mail
{
char un[25]; // user name
char pd[25]; // passsword
void reg(int);
} obj[5];
void mail::reg(int k)
{
int i=k;
clrscr();
cout<<"Enter user name ( enter unique name )\n";
cin>>un;
cout<<"Enter password\n";
cin>>pd;
ofstream filout;
filout.open("email",ios::app|ios::binary);
if(!filout) {
cout<<"cannot open file\n";
} else {
cout<<"\n "<<i;
filout.write((char *)&obj[i],sizeof(mail));
filout.close();
}
cout<<"You are now registered. \n";
getch();
} // end of sign up or register func
int main()
{
int t;
clrscr();
obj[0].reg(0);
obj[1].reg(1);
obj[2].reg(2);
mail obj2;
ifstream filein;
filein.open("email",ios::in|ios::binary);
if(!filein) {
cout<<"Unable to open file to read\n";
} else {
while(filein) {
filein.read((char *)&obj2,sizeof(obj2));
cout<<"username "<<obj2.un<<" passwword "<<obj2.pd<<"\n";
}
filein.close();
}
getch();
}
我仍然面临问题。我写了 3 个对象。但是我得到了 4 条输出记录。最后一个是重复的。