学过数据结构的不妨来看一看!

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;
}
...全文
44 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
六月初六 2003-07-29
  • 打赏
  • 举报
回复
因为在最后一次读写时 文件指针并未溢出!
所以eof判断未结束
在执行一次读的操作时
文件指针溢出!
所以eof总是让你多读一位
六月初六 2003-07-29
  • 打赏
  • 举报
回复
在读的时候在判断一次是否结束!
就着样!

69,368

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧