学过数据结构的不妨来看一看!
wmzlq 2003-07-29 08:41:11 想把一个链表保存在文件中,但是保存后再输出时出现了问题.(问题就出现在文件尾eof上面),跟踪调试,发现保存的是有两个节点的链表,但读出的是有三个节点的链表(最后多出的一个节点不符合),想问一下各位大虾,有没有一个好的方法来重载"<<"运算符才能避免这种失误....
#include<fstream.h>
struct Person //一个简单的结构体
{
int id;
char name[20];
Person* next;
};
void save(Person* &); //保存
void getout(Person* &); //从文件中读出重建链表
ostream& operator <<(ostream& oo,Person& d)
{
oo<<d.id<<" "<<d.name<<" "; //估计是这里出现了问题因导致对文件尾的判断出错
return oo;
}
istream& operator >>(istream& oo,Person& d)
{
oo>>d.id>>d.name;
return oo;
}
void main()
{
Person* List;
Person* &head=List;
Person* pS;
pS=new Person;
cout<<"请输入身份证号码:"<<endl;
cin>>pS->id;
cout<<"请输入姓名:"<<endl;
cin>>pS->name;
head=pS;
pS=new Person;
cout<<"请输入身份证号码:"<<endl;
cin>>pS->id;
cout<<"请输入姓名:"<<endl;
cin>>pS->name;
head->next=pS;
pS->next=NULL; //简单起见链表只有两个节点
save(head);
head=NULL; //为了验证getout函数,特意将head置为NULL
getout(head);
}
void save(Person* &head)
{
Person* pGuard;
fstream outfile("d:\\myprogram.txt",ios::out|ios::ate);
for(pGuard=head;pGuard!=NULL;pGuard=pGuard->next)
{
outfile<<*pGuard;
}
cout<<"已经被保存!"<<endl;
}
void getout(Person* &head)
{
fstream infile("d:\\myprogram.txt",ios::in);
Person* pGuard;
Person* pS;
pGuard=pS;
pS=new Person;
while(!infile.eof())
{
infile>>*pS;
if(head==NULL)
head=pS;
else
{
pGuard->next=pS;
}
pGuard=pS;
pS=new Person;
}
pGuard->next=NULL;
}