In that case I suppose I should just post it all. Thanks for helping me with this problem by the way.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /*to use strcpy*/
#include <stddef.h> /*to use NULL*/
#define N 4
#define SEED 1234567
struct words{
char word[N+1];
int used; /*If used is 1, word has been used and if used is 0, it has not.*/
};
typedef struct words WORDS;
struct treenode{
char data[N+1];
struct treenode *left;
struct treenode *right;
};
typedef struct treenode NODE;
WORDS words[1000]={0};
NODE data[N+1]={0};
FILE *W4;
NODE *root;
void getWords(void);
void printWords(void);
void randomWords(void);
NODE *insert(NODE *root, char *word);
void traverse(NODE *root);
int main(void)
{
getWords();
/*printWords();*/
randomWords();
root=NULL;
traverse(root);
system("PAUSE");
return 0;
}
void getWords(void)
{
int c=0, i=0, j=0; /*i increments words, j increments string*/
char string[N+1];
/*read in 1000 words from W4*/
W4=fopen("W4", "r");
while((c=getc(W4))!=EOF){
if(i!=1000){
if(c!='\n'&&c!=' ')
{
if(j==N){
i++;
string[j]='\0'; /*terminate string*/
/*printf("%s ", string);*/
strcpy(words[i].word, string);/*store string into an array*/
j=0; /*reset string incrementer to 0*/
string[j]=c; /*read in next character*/
j++;
}
else{
string[j]=c; /*read in a character*/
j++;
}
}
else
j=0;
}
}
fclose(W4);
printf("\n%d words have been put in the array words[1000].\n", i);
}
void printWords(void)
{
int i;
for(i=0;i<1000;i++)
printf("%s%d ", words[i].word, words[i].used);
}
void randomWords(void)
{
int i, randnum;
/* initialize random generator */
srand(SEED);
for(i=0;i<100;i++){
randnum=rand()%1000;
if(words[randnum].used!=1)/* generate a random number */
/*printf("%d:%d ", i+1, randnum);*/
/*printf("%s ", words[randnum].word);*/
insert(root, words[randnum].word);
words[randnum].used=1;
}
}
NODE *insert(NODE *node, char *word)
{
if(node==NULL){
node=(NODE *) malloc(sizeof(NODE));
strcpy(node->data, word);
node->left=NULL;
node->right=NULL;
}
else{
if(strcmp(word, node->data)<0)
insert(node->left, word);
else if(strcmp(word, node->data)>0)
insert(node->right, word);
}
return node;
}
void traverse(NODE *root)
{
if(root!=NULL){
traverse(root->left); /*recur left*/
printf("%s ", root->data);
traverse(root->right); /*recur right*/
}
}