This question already has an answer here:
here in this code i am creating a binary tree until user wants number of nodes. but while getting input from user it fails somewhere..
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");
this is not working properly
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:
When you press enter after entering a keyboard input - there stays in the buffer a trailing newline character which the next call on
scanf
reads.You have to just give one space before %c in scanf
This is because after giving the input we pressed enter that enter is stored in buffer and this read again by our program, some time we clear we flush our input/output buffer you can check in Linux
fflush()
I think so is the function, there is lots of way but this is the easiest way that I know. Hope useful for you.