C++ 文件问题

dddddddddddddddsad 2009-04-13 01:44:06
大家好!我写了一个文件,想把文件里的内容读到连表里,然后输出,文件里的内容为:
wangfutao
nan
23
24
luoyan
为什么总是出现内存错误啊。。请高手帮忙解决。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct people //定义一个用来存储人信息的结构体
{
string name;//姓名
int age; //年龄
string sex; //性别
string phone;//电话
string address;//住址
people *next;
//people():next(NULL){}
};
struct list
{
people *first;
people *last;
int length;
list():first(NULL),last(NULL),length(0){}
};
void ListAll(list &adrlist)
{
string name;
string sex;
int age=0;
string phone;
string address;
people *p=adrlist.first;
if(p==NULL)
{
cout<<"You address list is empty!"<<endl;
system("pause");
//main_menu();
}
else
{
while(p!=NULL)
{
cout<<" name: "<<p->name<<endl;
cout<<" age: "<<p->age<<endl;
cout<<" sex: "<<p->sex<<endl;
cout<<" phone: "<<p->phone<<endl;
cout<<"address: "<<p->address<<endl;
p=p->next;
}
}
//system("pause");
//main_menu();
}
list &Readin(ifstream &in,list &adrlist)
{
string name;
string sex;
int age=0;
string phone;
string address;
in.open("people.txt");
if(!in)
{
cout<<"cannot open the file!"<<endl;
exit(0);
}
people *q=new people;
in>>q->name>>q->sex>>q->age>>q->phone>>q->address;
adrlist.first=q;
people *p=adrlist.first;
while(!in.eof())
{
q=new people;
in>>q->name>>q->sex>>q->age>>q->phone>>q->address;
p->next=q;
p=q;
q->next=NULL;

}

in.close();
return adrlist;
}
int main()
{
list adrlist;
ifstream in;
adrlist=Readin(in,adrlist);
ListAll(adrlist);
return 0;
}
...全文
102 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
honglei8485 2009-04-15
  • 打赏
  • 举报
回复
没建议
aaaa3105563 2009-04-13
  • 打赏
  • 举报
回复
学习···
dddddddddddddddsad 2009-04-13
  • 打赏
  • 举报
回复
在c++里类和结构体除去默认的数据或成员的访问属性不同外,其他没什么不同。。故结构体也可以用new来申请空间的。。
firsthym 2009-04-13
  • 打赏
  • 举报
回复
而且你的内存正在泄露哦,一个new对应一个delete,其他人有建议吗?
firsthym 2009-04-13
  • 打赏
  • 举报
回复
people *q=new people;

people是结构体吧,不用new吧,又不是类
people* q;

65,211

社区成员

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

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