工大后院

 找回密码
 加入后院

扫一扫,访问微社区

QQ登录

只需一步,快速开始

搜索
查看: 1045|回复: 2

可以帮我优化一下这段代码吗?

[复制链接]
发表于 2007-1-10 21:13 | 显示全部楼层 |阅读模式
我想用一个函数完成学生信息的录入。可以调用一次函数输入多组数据
以下是我的代码
struct student
{
char num[15];char name[20];float eng,math,cpro;struct student*next,*pre;
};
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define L sizeof(struct student)
#define NULL 0
struct student*head ,*tail;
int count=0;\\学生个数

void input(void)
{
struct student*p;
printf ("请输入学生的信息,依次为学号、姓名、英语成绩、数学成绩、c语言成绩。以学号0结束输入\n");
do
{
  p=(struct student*)malloc(L);
  scanf("%s%s%f%f%f",p->num,p->name,&p->eng,&p->math,&p->cpro);
  count++;
  if (count==1) {head=p;tail=p;p->next=NULL;p->pre=NULL;}
  else
  {
   tail->next=p;p->pre=tail;p->next=NULL;tail=p;
  }
}
while(strcmp(p->num,"0")!=0);
tail=tail->pre;   
tail->next=NULL;
free(p);
}

由于我用的是do……while循环,所以每次调用函数输入结束后都有一个学号为0的空节点;所以每次调用函数都会多申请一个节点然后把它释放,效率很低。
但是用while循环,第一次输入时又不能判断
请问有什么好的方法吗?
发表于 2007-1-10 22:03 | 显示全部楼层
你可以在While之前做一次scanf呀
回复

使用道具 举报

 楼主| 发表于 2007-1-10 22:06 | 显示全部楼层
哦!明白了!谢谢,一时脑塞没想到!!
谢谢!!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 加入后院

本版积分规则

QQ|Archiver|手机版|小黑屋|广告业务Q|工大后院 ( 粤ICP备10013660号 )

GMT+8, 2025-5-15 15:39

Powered by Discuz! X3.5

Copyright © 2001-2024 Tencent Cloud.

快速回复 返回顶部 返回列表