-
Help! Stuck in a loop!
Hi!
I'm still working on my Binary search tree. I have to add words from a file to the tree in sibling or child branches. It seems my Addaword function is wokring a little better now, but something is stuck in an infinite loop. It'll read in the words, and repeat the last word over and over until it crashes.
I've changed a bunch of things to try and find out where, but I've only changed how it crashes. Can anyone see where my problem is? This is due soon, any help is much appreciated!
Code:
class Node
{
private:
Node *sibling;//*
Node *child;//*
int occurs;
char letters;
public:
AddAWord(char word[]);
Search(char request[]);
Node(char l) {occurs=0; sibling=0; child=0; letters=l;}
};
void main(void)
{
Node *root=new Node('-');
Node *new_node;
char word[80];
int len;
FILE*input;
char* request[10];
char str[80];
int i = 0, k=0, j=0, l=0;
ifstream b_file("abook.txt", ios::in);
b_file>>word;
for(j=0;j<strlen(word); j++)
{
word[j] = tolower((int)word[j]);
}
//root->AddAWord(word);
while( (b_file>>word) ) //b_file.eof()==0 || i<80)
{
// b_file>>word;
root->AddAWord(word);
for(int j=0; j<strlen(word); j++)
{
word[j] = tolower((int)word[j]);
}
new_node->AddAWord(word);
}
cout<<"What word would you like to search for: "<<endl;
cin>>str;
/* int x = root->Search(*request);
if(x<0)
cout<<"this word does not exist in the document!"<<endl;
else
cout<<"your word appeared "<< x <<" times in the document."<<endl;
*/
}
Node::AddAWord(char word[])
{
cout<<word<<endl;
//int i=0;
if(letters != word[0])
{
if(sibling)
sibling->AddAWord(word);
else if(sibling == 0)
{
sibling=new Node(*(word+1));
// i++;
sibling->AddAWord(word);
}
}
else if (letters ==*word+1)
{
if(word+1 != '\0')
{
if(child==0)
{child->AddAWord(word);}
else
{
child = new Node(*word);
//i++;
child->AddAWord(word+1);
}
}
else
occurs = occurs +1;
}
}
Node:: Search ( char request[] )
{
cout<<request<<endl;
if ( letters==*request )
child->Search(request);
else if ( letters!=*request )
sibling->Search(request);
else if(sibling == 0)
return 0;
else
return 1;
}
-
nitpicking here... no real solution...
so it only walks through the string once:
Code:
for(j=0;j<strlen(word); j++) //bad
/* this is better */
wordlen=strlen(word);
for(j=0;j<wordlen;j++)
what were you trying to do with this?
Code:
word[j] = tolower((int)word[j]);
IMO, the code looks better like this:
Code:
if(child==0)
{child->AddAWord(word);}
/* the curly's are unnecessary for one line for-loops and if statements */
for(j=0;j<wordlen;j++)
word[j] = tolower((int)word[j]);
...
if(child==0)
child->AddAWord(word);
-
If it get's stuck on the input loop, try changing the condition.
Code:
while(b_file.peek() != EOF)
{
//do whatever you need to do
}
I also notice you compare a single char with the first char of the search request. Are you doing this on purpose or are you trying to compare the arays like that?