Given an input string - named "strIn" - I need to find a string in a binary tree that begins with strIn. To test my code, I inputted "SAN", which should have caused my program to output "SANTORRO, KARREN". Instead, the loop returns a different value in the tree.
According to my debugger, the program gets to the correct leaf, but find() fails to find strIn within the leaf. Here is my code:
string bTreeClass::Search(string strIn)
{
string strOut;
// Binary trees are organized so that the lower leaf is on the left
// Start with the root leaf(current leaf is the root leaf
LeafClass *currentLeaf = rootLeaf;
// Loop until match found or current leaf has no links
while (true)
{
int find = currentLeaf->GetString().find(strIn);
// If strIn is in currentLeaf's string
if (currentLeaf->GetString().find(strIn) == 0)
// Match found
// Exit Loop
break;
// Else if search data is less than current leaf data
elseif (strIn.compare(currentLeaf->GetString()) < 0) {
// If current leaf does not have a left node
if (currentLeaf->GetLeftLink() == nullptr)
// Match failed
// Exit loop
break;
// Else current leaf does have a left node
else
// Advance current leaf to current leaf's left node
currentLeaf = currentLeaf->GetLeftLink();
// End if
}
// Else (search data is greater than current leaf data)
else {
// If current leaf does not have a right node
if (currentLeaf->GetRightLink() == nullptr)
// Match failed
// Exit loop
break;
// Else current leaf does have a right node
else
// Advance current leaf to current leaf's right node
currentLeaf = currentLeaf->GetRightLink();
// End if
// End if
}
// End loop
}
strOut = currentLeaf->GetString();
return strOut;
}
There is not enough context here to determine the cause of your issue. When asking others to troubleshoot your code, you should provide a minimal code sample that compiles and reproduces the problem that you are experiencing.
@cire: You're right. I found the reason why the code didn't work for me, and it was because of how my fellow programmer treated a TCHAR in the main code file. His code looked like this:
1 2 3
string strIn;
for (int i=0;i=MAX_LOADSTRING;i++)
strIn = strIn + (char)szString[i];
where szString is a TCHAR array.
Now, for future readers, casting a TCHAR to a char is dangerous, because a TCHAR can be either a char or a wchar_t, depending on how Visual Studio is set. The default setting is wchar_t. My fellow programmer had his copy of Visual Studio set to char, while mine was the default.
Fortunately, we can copy a wchar_t array into a char array using the wcstombs_s function.