Searching An Array In A Function

Hello!

[Note: This is a homework assignment. Just guidance on where my code is flawed and/or thoughts/suggestions/tips/etc. Thank you!]

I am having issues getting my search of an array to properly process within my function. (The assignment is to use a function to search an array.) The search feature works outside of the function, but not within. All the other sequences within the program work exactly the way I desire them to as well. Any help that can point me in the right direction to helping resolve this would be greatly appreciated!

Here's just the code I'm having issues with. It points back to two paralell user-defined arrays, 10 items per array. I can display them, just not search them. I'm using a looping menu, and when the user enters the menu option, the code returns:

Please enter a name to search for: .Your search for was not found.
(Followed by my menu prompt, which is the only thing it does properly.)

My call to the function is:

 
searchTel(telNo, name, 10);


The function is defined as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  void searchTel(long long telNo[], string name[], int numElem)
{
string soughtValue = " ";

cout << "\nPlease enter a name to search for: ";
getline(cin, soughtValue);

bool found = false;

//search
for (int x = 0; x < 10; x++)
{
if (soughtValue == name[x])
	{
	cout << endl;
	cout << name[x] << " : " << telNo[x] << endl;
	found = true;
	}
}

//display search results
if (!found)
{
cout << "Your search for " << soughtValue << " was not found.\n" << endl;
}

}
On line 17, after the result is found, the program should stop searching and break from the loop.

Line 11 is best to replace x < 10 with numElem.

In addition to what fiji885 has posted:

It would appear that you are searching for an empty string.

Line 6, getline(cin, soughtValue);
if the input buffer starts with a new line, the string that is read would be an empty string.

If that is the case, we need to extract and discard leading white space characters in the input buffer before attempting to read the string. For instance:
getline( cin >> std::ws, soughtValue );

In any case, print out a message immediately after the line which would help in understanding what is going on:
std::cout << "searching for name '" << soughtValue << "'\n" ;

Also, make the function const-correct:
void searchTel( const long long telNo[], const string name[], int numElem )
Last edited on
Thank you both so much! I implemented some of the steps you suggested - the break in the loop, and clearing the whitespace - and that seems to have done the trick! Thank you!!
Topic archived. No new replies allowed.