I am working on making tree using doubly linked list in c. I use recursive call in that function , but somehow it do not works. my code is :
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;
}
Run Code Online (Sandbox Code Playgroud)
here in the below function I am getting the problem.
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;
}
Run Code Online (Sandbox Code Playgroud)
the code compiles properly , but the problem is , the code do not wait for my choice (I use scanf() , C should wait untill I enter the input to the terminal.)
but the output is :
enter the value to the node4
is there any left child??
is there any right child??
Run Code Online (Sandbox Code Playgroud)
please assist.
The scanf("%d", &value) left a newline behind; the scanf("%c", &choice1) reads that newline.
Check the return values from scanf() every time. And print what you read to help you debug your code. Make sure your program got what you think it got.
A simple fix is to replace the second scanf() with scanf(" %c", &choice1). The blank in the format string eats up white space, including newlines, and reads the first non-blank character. Of course, it too leaves a newline behind.
As intimated in the comments, it is usually easier to control things with:
char line[4096];
if (fgets(line, sizeof(line), stdin) == 0)
...deal with EOF...
Run Code Online (Sandbox Code Playgroud)
And then you can use sscanf() to parse the line. This general technique is quite a bit less error prone than using scanf() directly; it is also a lot easier to report errors coherently when you have the whole line to include in the error report. That matters more when you're reading multiple conversions per call to scanf().