调了半天,都不知道哪里有错误了--
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct student )
struct student
{
char name;
int total;
struct student *next;
};
struct student *creat(void)
{
struct student *head;
struct student *p1,*p2;
int n=0;
head=NULL;
p1=p2=(struct student *)malloc(LEN);
scanf( "%c,%d ",&p1-> name,&p1-> total);
head=NULL;
while(p1-> name!= '@ '&&p1-> total!=0)
{
n=n+1;
if(n==1)head=p1;
else p2-> next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
scanf( "%c,%d ",&p1-> name,&p1-> total);
}
p2-> next=NULL;
return(head);
}
void output(struct student *p)
{
struct student *q;
q=p;
while(q!=NULL)
{
printf( "%c,%d\n ",q-> name,q-> total);
q=q-> next;
}
}
main()
{
struct student *q,*p;
q=creat();
if(q!=NULL);
output(q);
}
/*
I,90
A,80
C,97
U,86
@,0
*/
/*
而输出为:
I,90
,196984
A,80
,196984
C,97
,196984
U,86
,196984
Press any key to continue...
*/
为什么输出错误了?
[解决办法]
因为回车也被作为输入了,所以会有空行作为name,随机的int作为total
在scanf前面加fflush(stdin);
[解决办法]
fflush(stdin);
scanf( "%c,%d ",&p1-> name,&p1-> total);
[解决办法]
的确是楼上说的问题,把这里改一下:
while(p1-> name!= '@ ' && p1-> total!=0)
{
n=n+1;
if(n==1)
head=p1;
else
p2-> next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
fflush(stdin); //加一句这个,清空一下缓冲区
scanf( "%c,%d ",&p1-> name,&p1-> total);
}
[解决办法]
哇,学到了!!!谢谢!!
[解决办法]
当读入采用 字符读取的时候,比如getchar(), scanf( "%c " ..)的时候,需要注意滞留输入缓冲的回车符号。