![]() |
#2
veketdelphi2013-06-13 22:45
|

#include "stdafx.h"
#include "stdio.h"
#include<iostream>
using namespace std;
#define SIZE 4
typedef struct student_type
{
char name[10];
int num;
int age;
char addr[15];
struct student_type *next;
}STUD;
STUD *indata (STUD *,STUD *head);
void savef(STUD *,STUD *head);
void loadf(STUD *,STUD *head);
void display(STUD *,STUD *head);
int main(int argc, char* argv[])
{ STUD *st,*so,*head;
head=st=so=(STUD *)malloc(4*sizeof(STUD));
indata(st,head);
savef(st,head);
loadf(so,head);
display(so,head);
return 0;
}
STUD *indata(STUD *s,STUD *head)
{short i;
STUD *snext;
cout<<"Input name num age addr for 4 students"<<endl;
scanf("%s %d %d %s",head->name,&head->num,&head->age,head->addr);
for(i=1;i<SIZE;i++)
{ snext=(STUD *)malloc(sizeof(STUD));
scanf("%s %d %d %s",snext->name,&snext->num,&snext->age,snext->addr);
s->next=snext;
s=snext;
}
s->next=NULL;
return head;
}
void savef(STUD *s,STUD *head)
{
FILE *fp;
if((fp=fopen("d://stu.txt","wb"))==NULL)
{cout<<"erro"<<endl;
return;
}
for(s=head;s->next!=NULL;s=s->next)
{fwrite(s,sizeof(STUD),1,fp);
}
fclose(fp);
}
void loadf(STUD *s,STUD *head)
{
FILE *fp;
if((fp=fopen("d://stu.txt","rb"))==NULL)
{fprintf(stdin,"cannot open file\n");
return;
}
for(s=head;s->next!=NULL;s=s->next)
fread(s,sizeof(STUD),1,fp);
fclose(fp);
}
void display(STUD *s,STUD *head)
{
cout<<"Output..."<<endl;
for(s=head;s->next!=NULL;s=s->next)
{
cout<<s->addr<<" "<<s->num<<" "<<s->age<<" "<<s->name<<" "<<endl;
}
}
程序输出然后在D://stu中显示的是乱码。。。这是为什么啊?我是在一本书上看见的,书上用的是数组,然后我想改成动态的指针来进行操作,然后就出现这样的问题了。小白求指点!