C语言高手进来帮看下

我在做练习,写一个动态的单向链表,实现创建,删除功能,创建链表完成后,输入数据时,出现了问题,我把代码发出来,前辈们帮看看,问题出在哪?
#include <stdio.h>#include <malloc.h>
#define LEN sizeof(struct student)
struct student *creat();struct student *delet(struct student *head,int a);void print(struct student *head);
int n;
struct student{ int num; float score; struct student *next;};
void main(){ struct student *p,*y; int b; p=creat(); printf("请输入要删除的结点:"); scanf("%d",&b); y=delet(p,b); print(y); }
struct student *creat(){ struct student *head,*p1,*p2; p1=p2=(struct student *)malloc(LEN); n=0; head=NULL; printf("请输入学号:"); scanf("%d",&p1->num); printf("请输入分数:"); scanf("%f",&p1->score);//这一步的时候,就出现问题了,把%f改成%d,把上面struct student里的float score改成int,就没问题了,这是什么回事呀 while(p1->num!=0) { n++; if(n==1) { head=p1; } else { p2->next=p1; } p2=p1; p1=(struct student *)malloc(LEN); printf("请输入学号:"); scanf("%d",&p1->num); printf("请输入分数:"); scanf("%f",&p1->score); }
free(p1); p2->next=NULL;
return head;}
struct student *delet(struct student *head,int a){
}
void print(struct student *head){
}
我把运行后出问题的图片贴出来,前辈们帮看看,是怎么回事

你的这个问题我一起也遇到过,它跟输入输出缓冲区有关。具体自己研究。
解决的话就是
printf("请输入学号:\n");
scanf("%d",&p1->num);
printf("请输入分数: \n");
scanf("%f",&p1->score);
这样在后面换行就好。
也有清空缓冲区的函数,我不是很会用。
fflush(stdin);//清空输入缓冲区
fflush(stdout);//清空输出缓冲区
可追问。追问

加了\n还是不行呀。。。

追答

确实是环境的问题,好了,教你个办法:
把代码拷贝一下,重新编译就好了。不要太认真,这种事浪费时间。
#include
#include
#define LEN sizeof(struct student)
struct student *creat();
struct student *delet(struct student *head,int a);
void print(struct student *head);
int n;
struct student
{
int num;
float score;
struct student *next;
};
void main()
{
struct student *p,*y;
int b;

p=creat();

printf("请输入要删除的结点:");
scanf("%d",&b);

y=delet(p,b);

print(y);

}
struct student *creat()
{
struct student *head,*p1,*p2;

p1=p2=(struct student *)malloc(LEN);

n=0;

head=NULL;
printf("请输入学号:");
scanf("%d",&p1->num);

printf("请输入分数:");
scanf("%f",&p1->score);

while(p1->num!=0)
{
n++;
if(n==1)
{
head=p1;
}
else
{
p2->next=p1;
}

p2=p1;

p1=(struct student *)malloc(LEN);

printf("请输入学号:");
scanf("%d",&p1->num);

printf("请输入分数:");
scanf("%f",&p1->score);
}

free(p1);
p2->next=NULL;

return head;
}
struct student *delet(struct student *head,int a)
{
return head;
}
void print(struct student *head)
{

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-09-19
scanf 函数遇到 其他标点符号或者空格 比如 浮点数 中的 点. 就会认为你输入完毕了。导致 点后面的值再次跑到 printf("请输入学号:");
scanf("%d",&p1->num);里面。你可以换一个从屏幕读取数值的函数,不用scanf 。 这样就可以了。追问

我用getchar(p1->score),但是不给输入,,

追答

getchar 是从屏幕获取一个字符。兄弟。你用错了。

追问

那应该换哪个呀?,,

第2个回答  2013-09-19
建议更换编译环境。追问

我的代码应该没有问题吧?上一次做练习时这样还行,现在就不行了,,

相似回答