我正在使用c中的双向链表来制作树。 我在该函数中使用递归调用,但不知何故它不起作用。 我的代码是:scanf()不在等待用户输入
struct node
{
int data;
struct node *right;
struct node *left;
};
struct node* getNode()
{
struct node *temp;
temp= (struct node *)malloc(sizeof(struct node));
temp->right=NULL;
temp->left=NULL;
return temp;
}
这里在下面的功能我得到的问题。
struct node* maketree()
{
struct node *t;
t=getNode();
int value;
char choice1='n',choice2='n';
printf("\nenter the value to the node");
scanf("%d",&value);
t->data=value;
printf("\nis there any left child??\n");
scanf("%c",&choice1); // I think here my problem is .
if (choice1 == 'y')
{
t->left=maketree();
}
printf("\nis there any right child??\n");
scanf("%c",&choice2);
if (choice2 == 'y' || choice2 == 'Y')
{
t->right=maketree();
}
return t;
}
int main (void)
{
struct node *t;
t=maketree();
return;
}
代码编译正确,但问题是,代码不等待我的选择(我用scanf()
,C应该等待,直到我进入输入端子)。 但输出是:
enter the value to the node4
is there any left child??
is there any right child??
请协助。
如果您检查了'scanf()'验证的返回码,那么您现在可能已经发现了该问题。 – WhozCraig
Aaaaaand kaboom。如果你不明白它是如何工作的,使用'fgets()'和**离开'scanf()'**。这不是初学者的功能。 – 2013-08-22 05:41:53
[scanf第二次不会要求输入]的可能重复(http://stackoverflow.com/questions/13372923/scanf-wont-ask-for-input-the-second-time)以及[Program doesn不要等待用户输入scanf(“%c”,&yn);](http://stackoverflow.com/questions/8464620/program-doesnt-wait-for-user-input-with-scanfc-yn)和[为什么scanf在一次失败后不等待用户输入?](http://stackoverflow.com/questions/11805414/why-does-scanf-not-wait-for-user-input-after-it-fails-一次性) – 2013-08-22 05:45:56