-
LL Search Function
I'm writing a simple LL search function, which will search through the linked list for a Name. If found, it will print out the Name and ID associated with the name, and continue searching.
I stepped through the function in VStudio and it recognizes what it is comparing and the input, but it is not saying they are equal for some reason, and I cannot figure out why.
Code:
void LList::search(char Name[]) {
int num_found=0;
People * temp;//allocate memory for struct
temp = first;//fill struct with contents of first struct in list
if (entries == 0) {
cout << "List is empty, nothing to search!\n";
return;
}//if
cout << "Search Results for "<< Name << ":\n";
while (temp != NULL) {
if (temp->Name == Name) {//if name found
cout << temp->Name << " " << temp->ID << endl;
num_found++;
}//if
temp = temp->Next;//traverse the list
}//while
cout << "Found " << num_found << " entries.\n";
}//search
I've been testing things with simple statements:
list.add_entry("A", 1);
list.search("A");
My add_entry, print_list, delete_entry functions all seem to work fine, but this simple one has something going on I am having trouble finding. Any ideas?
-
Code:
void LList::search(char Name[]) {
int num_found=0;
People * temp;//allocate memory for struct
temp = first;//fill struct with contents of first struct in list
if (entries == 0) {
cout << "List is empty, nothing to search!\n";
return;
}//if
cout << "Search Results for "<< Name << ":\n";
while (temp != NULL) {
if (temp->Name == Name) {//if name found
cout << temp->Name << " " << temp->ID << endl;
num_found++;
}//if
temp = temp->Next;//traverse the list
}//while
cout << "Found " << num_found << " entries.\n";
}//search
You can't compare c-style strings (null terminated char arrays) using operator==. You need to use strcmp. You probably would benefit from using std::string containers instead which would support the use of operator==.
-
You're comparing pointers, not the data that is "pointed to".
Soma
-