有关链表问题:将文件中的数据读入到链表中在打印到屏幕上最后一行总出现乱码求高手!...
#include<iostream>#include<fstream>
#include<stdlib.h>
using namespace std;
struct advices
{
char adv[100];
advices *next;
};
advices *adread()
{
advices *p,*q,*head;
FILE *fp;
head=new advices;
if(head==NULL)
{
cout<<"开辟失败!!"<<endl;
exit(1);
}
q=head;
if((fp=fopen("15.txt","rb"))==NULL)
{
cout<<"系统无信息请稍后建立!!!"<<endl;
return head;
}
fread(q,sizeof(advices),1,fp);
while(!feof(fp))
{
if((p=(advices *)malloc(sizeof(advices)))==NULL)
{
cout<<"读取失败!!"<<endl;
exit(1);
}
fread(p,sizeof(advices),1,fp);
q->next=p;
q=p;
}
q->next=NULL;
fclose(fp);
return head;
}
int main()
{
FILE *fp;
advices *p;
advices *head,*p1,*p2;
head=new advices;
p1=head;
for(int i=0; ;i++)
{
p2=new advices;
cout<<"请在此写下你的留言以q退出\n====>>>>"<<endl;
cin>>p2->adv;
if((strcmp(p2->adv ,"q"))==0)
{
free(p2);
break;
}
p1->next=p2;
p1=p2;
}
p1->next=NULL;
p=head;
if((fp=fopen("15.txt","wb"))==NULL)
{
cout<<"打开失败!!"<<endl;
return 0;
}
while(p)
{
fwrite(p,sizeof(advices),1,fp);
p=p->next;
}
cout<<"信息保存成功!!"<<endl;
fclose(fp);
head=adread();
head=head->next;
while(head)
{
cout<<head->adv<<endl;
head=head->next;
}
return 0;
}