In Windows i used flushall() function to flush all the buffers but this doesnt work in Linux, my scanf() function skips without scanning:
for(i=0;i<n;i++)
{
printf("\nEnter alphabet :");
scanf("%c",&x);
printf("\nEnter frequency :");
scanf("%f",&probability);
/* create a new tree and insert it in
the priority linked list */
p=(treenode*)malloc(sizeof(treenode));
p->left=p->right=NULL;
p->data=x;
p->freq=(float)probability;
head=insert(head,p);
}
Output :
mayur@mayur-laptop:~$ ./a.out
Enter alphabet :a
Enter frequency :2
Enter alphabet :
Enter frequency :a
Enter alphabet :
Enter frequency :2
Enter alphabet :
Enter frequency :a
Enter alphabet :
You should add a space on the beginning of the scanf
, and fflush(stdin)
before every scanf
just to clear the standard input buffer (keyboard by default), like this:
for(i=0;i<n;i++){
printf("\nEnter alphabet :");
fflush(stdin);
scanf(" %c",&x);
printf("\nEnter frequency :");
fflush(stdin);
scanf(" %f",&probability);
/* create a new tree and insert it in
the priority linked list */
p=(treenode*)malloc(sizeof(treenode));
p->left=p->right=NULL;
p->data=x;
p->freq=(float)probability;
head=insert(head,p);
}
EDIT: check if you have char x
and float probability
Update: The OP changed the "%d"in the first scanf to "%c" which lets the error, I think, occur later; but franky, I don't feel investing any more time here.--
Original answer: The input is never processed beyond the 'a' because you try reading it with the conversion specification %d for integer numbers which it doesn't satisfy. (In order to read a char you would specify %c.) Scanf puts the offending character back in the input and tries to read the next number which fails again, and so on ad eternum.
It's worth checking scanf's return value which will always be 0 here, indicating that no successful conversion has taken place.