在这段代码中,我正在创建一个二叉树,直到用户想要节点数。
但是在从用户获取输入时,它在某个地方失败了..
struct node *createTree(struct node *root)
{
int n;
char ch;
struct node *t1;
t1=(struct node *)malloc(sizeof(struct node));
printf("Enter Element\n");
scanf("%d",&n);
if(root==NULL)
{
t1->data=n;
t1->left=NULL;
t1->right=NULL;
root=t1;
}
printf("do you want to add node at left?\n");
这不能正常工作
scanf("%c",&ch);
if(ch=='y')
{
t1->left=createTree(t1->left);
}
printf("do you want to add node at right?\n");
scanf("%c",&ch);
if(ch=='y')
{
t1->right=createTree(t1->right);
}
return root;
}
Do this:
printf("do you want to add node at right??!\n");
scanf("%c",&ch);
while (getchar()!='\n'); //<-- eat up trailing newline chars - Reads all characters of the line until the end of line is found.
当您在输入键盘输入后按 Enter 时 - 缓冲区中会保留一个尾随换行符,下一次调用该换行符scanf
reads.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)