The user inputs a name they want to search for in my arrays if it matches one in the list I want it to output the location in the array that the name is located.
However when I enter my target name my program just stalls and nothing outputs. Any help or insight would be much appreciated, a nudge in the right direction and I'll think I'll have it. Thanks so much in advance!
See that semi-colon? It marks the end of the block of code that is executed in the while loop. So your while loop is empty. It will loop forever, because your while loop contains no code so a never changes.
Remove that semi-colon. Right now, your function looks like this:
int search (string names[], string target)
{
int a = 0;
while ((a<1000) && (target != names[a])); // Loop forever
// This code will never be reached
{
if (target == names[a])
return a;
else a++;
}
}
Thanks @Moschops, I am now getting a value for my cout << loc statement, however when I input a name such as Justin which is allocated to 73 in the boys array it is returning 0 as the answer it deals with this block of code
1 2 3 4 5 6 7
int search (string names[], string target){
int a = 0;
while (a<1000);{
if (target == names[a])
return a;
else a++;
}
See that semi-colon? It marks the end of the block of code that is executed in the while loop. So your while loop is empty. It will loop forever, because your while loop contains no code so a never changes.
int search (string names[], string target)
{
cout << "Entering search function, search target: " << target << endl;
int a = 0;
while (a<1000)
{
cout << "In loop, a = " << a << endl;
if (target == names[a])
{
cout << "Found target in location " << a << endl;
return a;
}
else
{
a++;
cout << "Incrementing a, a is now " << a <<endl;
}
} // I HAD TO ADD THIS CLOSING BRACE BECAUSE YOUR CODE DIDN'T HAVE ONE
// WHERE IS THE RETURN FOR WHEN THE STRING IS NOT FOUND?
}
Note that if the string is not found, you have no return statement, so the returned value could be anything. This function is malformed.