c++ 链表输出文件中的数据

blueshaw 2009-11-08 03:52:05
#include<fstream.h>

struct student
{
long int num;
char name[8];
char sex[2];
int age;
char major[8];
student *next;
};

student *creatlist()
{
student *head=NULL,*tail=NULL;
student *p=NULL;
fstream file1;
file1.open("data.txt",ios::in|ios::binary);
while(!file1.eof())
{
p=new student;
file1>>p->num>>p->name>>p->sex>>p->age>>p->major;
if(head==NULL)
head=p;
else
tail->next=p;
tail=p;
}

delete p;
tail->next=NULL;
file1.close();
return head;
}


void showlist(student *head)
{
student *tail;
tail=head;
while(tail)
{
cout<<tail->num<<" "<<tail->name<<" "<<tail->sex<<" "<<tail->age<<" "<<tail->major<<endl;
tail=tail->next;
}
}

void main()
{
student *head=NULL;
head=creatlist();
showlist(head);
}

data中为:
01 张三 男 19 通信1082
02 李四 男 20 通信1082
03 王二 男 20 通信1082
我的程序能输出前面两条信息,最后一条信息输出的是 -572662307 葺葺葺葺葺葺葺葺葺葺葺葺 葺葺葺葺葺葺葺葺 -572662307 葺葺葺葺

请高手指点啊,我的程序哪错了。
我用的是vc6.0的
...全文
152 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
blueshaw 2009-11-08
  • 打赏
  • 举报
回复
问题解决了
mengde007 2009-11-08
  • 打赏
  • 举报
回复
delete p;
你释放了最后一个节点;
bitxinhai 2009-11-08
  • 打赏
  • 举报
回复
while(!file1.eof())
{
p=new student;
file1>>p->num>>p->name>>p->sex>>p->age>>p->major;
if(head==NULL)
head=p;
else
tail->next=p;
tail=p;
}

delete p;//去掉看看。。

64,636

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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