新手小菜来虚心求教,请大家帮忙看看这段代码都哪里错了

g975291783 2013-03-19 10:26:19
#include<stdio.h>
#include<stdlib.h>
# define len sizeof(stu)
FILE *fp;
struct stu
{
int ID;
char name[20];
char sex;
int C;
int Eng;
int total;
stu *next;
};
stu *input(stu *head)
{
stu *p1=NULL,*p2=NULL;
int n=0;
p1=(stu *)malloc(len);
p2=p1;
if(p1==NULL)
{
printf("对不起,节点空间申请失败");
return NULL;
}
if(head==NULL)
head=p1;
else
{
printf("请开始输入学生信息\n");
printf("输入格式(学号 姓名 性别(m/w) C成绩 英语成绩)\n");
while(p1->ID!=0)
{
printf("请输入第%d个学生信息:",n+1);
scanf("%d",&p1->ID);
scanf("%s",p1->name);
getchar();
scanf("%c",&p1->sex);
scanf("%d",&p1->C);
scanf("%d",&p1->Eng);
getchar();
p1->total=p1->C+p1->Eng;
n++;
if(p1->ID==0)
{
p1->next=NULL;
return head;
}
else
{
p2=p1;
p1=(stu *)malloc(len);
p2->next=p1;
}
}


}
}
void writetofile(stu *head)
{
stu *p;
p=head;

if((fp=fopen("D:\\student.txt","a"))==0)
{
printf("文件打开失败");
exit(0);
}
do{

fwrite(&p,len,1,fp);printf("数据已经成功写入D:\\student.txt中");
p=p->next;
}while(p->next=NULL);
printf("数据已经全部成功写入D:\\student.txt中");
}
void output(stu *head)
{
stu *p;
p=head;
while(p->next!=NULL)
{
printf("%d\t",p->ID);
printf("%s\t",p->name);
printf("%c\t",p->sex);
printf("%d\t",p->C);
printf("%d\t",p->Eng);
printf("%d\t",p->total);
printf("\n");
p=p->next;
}
}
void main()
{
int n;
stu *head;

head=input(head);

writetofile(head);
output(head);


}

这是我们老师留得一个作业,让做一个学生信息管理(真的是很老的题目了。。呵呵)。这是我写的一部分代码,编译没错,但是一运行程序就会死掉。自己看了好久也没找出错误。请大家帮忙看看。。
...全文
94 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
g975291783 2013-03-20
  • 打赏
  • 举报
回复
多谢,问题的确出在那两个地方,现在问题已经解决了。
_sunshine 2013-03-20
  • 打赏
  • 举报
回复

stu* input(stu *head)
{
	stu *p1=NULL,*p2=NULL;
	int n=0;
	p1=(stu *)malloc(len);
	p2=p1;
	if(p1==NULL)
	{
		printf("对不起,节点空间申请失败");
		return NULL;
	}
	if(head==NULL)
		head=p1;
	else
	{
		printf("请开始输入学生信息\n");
		printf("输入格式(学号 姓名 性别(m/w) C成绩 英语成绩)\n");//此处没有输入p1->ID
		while(p1->ID!=0)
		{
			printf("请输入第%d个学生信息:",n+1);
			scanf("%d",&p1->ID);
			scanf("%s",p1->name);
			getchar();
			scanf("%c",&p1->sex);
			scanf("%d",&p1->C);
			scanf("%d",&p1->Eng);
			getchar();
			p1->total=p1->C+p1->Eng;
			n++;
			if(p1->ID==0)
			{
				p1->next=NULL;
				return head;
			}
			else
			{
				p2=p1;
				p1=(stu *)malloc(len);
				p2->next=p1;
			}
		}
	}
}
void writetofile(stu *head)
{
	stu *p;
	p=head;

	if((fp=fopen("D:\\student.txt","a"))==0)
	{
		printf("文件打开失败");
		exit(0);
	}
	do{

		fwrite(&p,len,1,fp);printf("数据已经成功写入D:\\student.txt中");
		p=p->next;
	}while(p->next=NULL);//此处应该是!=
	printf("数据已经全部成功写入D:\\student.txt中");
}
稍微看了下楼主的代码,有两处明显错误已经在上面注释,楼主可以调试,看哪一步错了

64,639

社区成员

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

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