我已经开始用C编写链表了。我的代码如下:
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
};
struct node * create(struct node *);
display(struct node *);
int main()
{
struct node *head=NULL;
head = create(head);
display(head);
getch();
return 0;
}
struct node * create(struct node *Head)
{
struct node *temp;
char ch='y';
int i=1;
while(ch=='y')
{
temp=malloc(sizeof(struct node));
temp->data=i*10;
temp->next=Head;
Head=temp;
printf("\nAdded node : %d",Head->data);
printf("\nContinue to add more nodes ? : ");
scanf("%c",&ch);
}
return Head;
}
display(struct node *Head)
{
while(Head!=NULL)
{ printf("%d\t%d\n",Head->data,Head->next);
Head=Head->next;
}
}
我面临的问题是,在进入“create”函数并只创建一个节点后,我的程序跳回到main,然后跳转到“display”函数,然后跳回到“create”函数。它询问我是否要继续的行。此时,当我输入“y”时,程序就退出了! 为什么会有这种行为?? 有人请给我解释一下控制是如何流动的和为什么我的程序会失控!!!
最佳答案
原因:
发生这种情况是因为当您输入 'y'
然后按回车键时,换行符 '\n'
会被缓冲并在下一次迭代时读取扫描()
。这将导致 while(ch=='y')
评估为 false
(从现在开始 ch == '\n'
),中断脱离循环。
通常 scanf()
会在达到预期值之前跳过空格和换行符。但是,当您使用字符格式 %c
时,这不会发生,因为换行符和空格也是有效字符。
如何修复:
您可以使用 scanf("%c",&ch);
修复它。 %c
之前的空格将跳过在实际读取值之前在缓冲区中找到的任何前导退格符或换行符。
关于c - while() 循环未按预期工作。可能是什么原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24334672/