My two issues with my program is that; first, When the user is entering their words, the duplicate error message only apears if it is the first word they enter(ie...)
Code:
enter a word : bill
enter a word : steve
enter a word : frank
enter a word : bill
duplation found, ignored
enter a word : steve
enter a word :
Doesn' the while(fgetc(stdin)!='\n' remove everything in the buffer?
Secondly the addess's of the names are being returned on the nodes, I'm aware it is a simple pointer error but I cannot put my finger on it.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define merror() {printf("memory allocation problem\n"); exit(1);}
struct NODE_STRUCT
{
char* name;
struct NODE_STRUCT *left, *right;
};
typedef struct NODE_STRUCT NODE;
NODE* TREE=0;
NODE* Insert(NODE* t,char* name);
void Display(NODE* t);
void Display1(NODE* node);
NODE* MakeNode(char *name)
{
NODE* t;
t=(NODE*)malloc(sizeof(NODE));
t->name=(char*)malloc(strlen(name)+1);
strcpy(t->name,name);
t->left=t->right=0;
return t;
}
/* function main ---------------------------------------------------- */
int main()
{
int m,k;
char name[21];
printf("Do not enter more than 20 characters and type 'quit' at any time to finish.\n");
while(1)
{
printf("Enter a word: ");
fflush(stdout);
for(m=0; m<21; m++)
{
name[m]=(char)fgetc(stdin);
if (name[m]=='\n')
{
name[m]='\0';
break;
}
}
if (m>=21)
{
printf("Word is more than 20 characters.\n");
while(fgetc(stdin)!='\n');
continue;
}
if (m==0)
{
printf("That input is empty\n");
continue;
}
if (strcmp(name,"quit")==0)
break;
TREE=Insert(TREE,name);
}//While loop
Display(TREE);
return 0;
}
/* function Insert ---------------------------------------------------- */
NODE* Insert(NODE* t,char* name)
{
int value;
NODE* p;
if (t==0)
{
t=MakeNode(name);
return t;
}
p = t;
value=strcmp(p->name, name);
while(1)
{
if (value<0)
{
if (p->left==0)
{
p->left=MakeNode(name);
return t;
}
else
{
p=p->left;
continue;
}
}
else if (value==0)
{
printf("duplaicate value, ignored\n");
return t;
}
else
{
if (p->right==0)
{
p->right=MakeNode(name);
return t;
}
else
{
p=p->right;
continue;
}
}
}
return 0; // just to make compiler happy
}
/* function Display ----------------------------------------------------- */
void Display(NODE* t)
{
if (t==0)
{
printf("tree is empty\n");
return;
}
else
Display1(t);
}
/* function Display1 ----------------------------------------------------- */
void Display1(NODE* t)
{
if (t==0)
return;
Display1(t->left);
printf("%d\n",t->name);
Display1(t->right);
}