本帖最后由 q541767950 于 2014-1-16 22:10 编辑
我是前段时间才开始学习的C语言,感觉基本入门,就自己编写了一段练练手,把学过的部分基本都用上了,但是运行调试的时候大部分问题都解决了,但是不知道为什么运行还是有一个错误解决不了。以下是程序原文:
#include
#include
struct people
{
int ID;
char name[20];
int age;
char sex;
struct people *point;
};
struct people *create( int n)
{
int i;
struct people *pb,*pf,*head;
for (i=1;i<=n;i++)
{
pb=(struct people *)malloc(sizeof(struct people));
if(i==1)
head=pf=pb;
pf->point=pb;
pb->point=NULL;
pf=pb;
}
return head;
}
void input(struct people *head,int n)
{
int i;
char filename[20];
FILE *fp1;
struct people *ptr=head;
for(i=1;i<=n;i++)
{
printf("请输入姓名,年龄,性别(格式:姓名,年龄,性别[m/f])");
scanf("%s,%d,%c",ptr->name,&ptr->age,&ptr->sex);
ptr=ptr->point;
}
printf("请输入保存文件名(*.bat)");
scanf("%s",filename);
if(((fp1=fopen(filename,"w"))==NULL))
{
printf("File can not open!\n");
exit(0);
}
ptr=head;
do
{
fwrite(ptr,sizeof(struct people),1,fp1);
ptr=ptr->point;
}
while(ptr!=NULL);
fclose(fp1);
printf("数据写入完毕");
}
void exfree(struct people *head)
{
struct people *tmp;
do
{
tmp=head->point;
free(head);
head=tmp;
}
while(head!=NULL);
}
void output(char filename[20])
{
FILE *fp2;
struct people *ptr;
if(((fp2=fopen(filename,"r"))==NULL))
{
printf("File can not open!\n");
exit(0);
}
printf("\t姓名\t年龄\t性别\t\n");
do
{
ptr=(struct people *)malloc(sizeof(struct people));
fread(ptr,sizeof(struct people),1,fp2);
printf("\t%s\t%d\t%c\t\n",ptr->name,ptr->age,ptr->sex);
free(ptr);
}
while(!feof(fp2));
fclose(fp2);
}
void main()
{
int i,n;
struct people *date;
char filename[20];
do
{
printf("请输入编号执行以下程序:\n1.创建表并录入数据\n2.读取表\n3.结束程序\n");
scanf("%d",&i);
switch(i)
{
case 1:
printf("请输入记录条数:");
scanf("%d",&n);
date=create(n);
input(date,n);
exfree(date);
break;
case 2:
printf("请输入文件名:");
scanf("%s",filename);
output(filename);
break;
case 3:
break;
default:
printf("输入错误,请重新输入");
}
}
while(i!=3);
return;
}
我自己看了好像是input函数块的scanf函数使用出错,但是就是不知道哪错了,不知道是格式化输入出错还是哪里,输入数据老是都存储在ptr->name下,而不是三个变量里,我确定有用美式键盘输入分隔符“,”。希望有人能帮我解决下。
菜鸟敬上。。。