This function of my program is supposed to find the terms in a sorted array that match the key that the user is searching for. This is an autocomplete program. It is supposed to store the first location of the term that first matches the key and then the last so then I can make a new list made up of those terms in another function to print to the screen. And I tested a bit to try to see what was giving me the wrong results.
void Autocomplete::BinarySearch(string key, int& first, int& last) {
bool firstFound = false;
bool lastFound = false;
int keylen = key.length(); //equals 2, for testing purposes
for (int i = 0; i < size - 1; i++) {
cout <<p[i].query.substr(0,2) << endl; // testing this gave me the wrong
//results, it should print the first
//two letters of each term but it
//gives me weird characters
if (key == p[i].query.substr(0, 2)) {
firstFound = true;
first = i;
}
if (firstFound == true && (p[i].query.substr(0, key.length()) != key)){
lastFound = true;
last = i-1;
break;
}
}
}
Sorry. p is a pointer to an array of terms, each consisting of a string and an int. query is referring to the string in of a term in the array. I figured it out though. For some reason substr(1, any other number) works. 0 doesn't which is weird to me.