Sorting and finding strings.

I am working on an assignment that allows the program to ask the user to input a name in the last name "comma" first name format, (e.g. "Collins, Bill"). The input is then searched a pre-defined array. So, first I'm trying to sort the array, and then include the search function (search using binary search). After I coded it, it never finds the names that I have in the array and always says that the name was not found. Please help me! The code is below:


#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

//Function Prototypes:
int binaryNameSearch(string [], int, string);
void sortNames(string[], int);

int main()
{
const int SIZE = 20;

string name[SIZE] = { "Collins, Bill", "Smith, Bart", "Michalski, Joe",
"Griffin, Jim", "Sanchez, Manny", "Rubin, Sarah",
"Taylor, Tyrone", "Johnson, Jill", "Allison, Jeff,",
"Moreno, Juan", "Wolfe, Bill", "Whitman, Jean",
"Moretti, Bella", "Wu, Hong", "Patel, Renee",
"Harrison, Rose", "Smith, Cathy", "Conroy, Pate",
"Killy, Sean", "Holland, Beth"};
string NameSearch;
int name_search;

//Sorting the names in alphabetical order
sortNames(name, SIZE);

//Get user input for name
cout << "Enter the name you wish to find: ";
cin >> NameSearch;
cout << endl;

name_search = binaryNameSearch(name, SIZE, NameSearch);
if (name_search = -1)
{
cout << "The name you searched for does not exist. ";
}
else
{
cout << "You searched for " << NameSearch << ", and it was found in ";
cout << "the array.\n\n";
}

return 0;
}

void sortNames(string namesorting[], int names)
{
string tempName;
for(int namesearch = 0; namesearch < names - 1; namesearch++)
{
for(int found = 0; found < names - 1; found++)
{
if (namesorting[found] > namesorting[found+1])
{
tempName = namesorting[found];
namesorting[found] = namesorting[found + 1];
namesorting[found + 1] = tempName;
}
}
}
}

int binaryNameSearch(string nameSearchedfor[], int names, string input)
{
int first = 0,
last = names - 1,
middle,
position = -1;

bool found = false;

while(!found && first <=last)
{
middle = (first + last)/2;
if (nameSearchedfor[middle] == input)
{
found = true;
position = middle;
}
else if (nameSearchedfor[middle] > input)
{
last = middle - 1;
}
else
{
first = middle + 1;
}

}
};
Also, I am not allowed to use pointers because we haven't covered that chapter in class.
No help for me? :(
Hi,
Few changes:
1)
Instead of using >> use getline to enter name i.e.
replace
cin >> NameSearch;
by
getline(cin,NameSearch);
2)Function binaryNameSearch should return a value.
3)One silly error:
1
2
name_search = binaryNameSearch(name, SIZE, NameSearch);
if (name_search = -1) 

should have been

if (name_search == -1)

I ran ur code with above changes.It works fine.



Topic archived. No new replies allowed.