How do I search the whole array?

Program is a list of names and asks the user to input one and tells them if its in there or not.

If I enter the first name(search) and set if (names[0] == search)the program works perfectly yes or no.

If If I enter the first name(search) and set if (names[i] == search)the program blows up.

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
29
30
31
32
33
34
35
 	int i = 0;
	string search;
	string names[100];
	ifstream read;

	read.open("names.txt");
	if (read.fail())
	{
		cout << "Input file opening failed.\n";
		exit(1);
	}


	while (read >> names[i])
		i++;

	cout << "Enter a name that may be in the file." << endl;
	cin >> search;

	for (int j = 0; j <= i; j++)
	{

		if (j=i)
		{
			if (names[0] == search)
			cout << "Congrats, the name is in the file!" << endl;
			
			else
				cout << "Sorry, the name is NOT in the file." << endl;
		}
		
	}


		read.close();
Line 20: You want the termination condition to be j<i. Otherwise you're going to index past the last valid entry.

Line 23: You don't want this if condition.

Line 25: You want to compare names[j]

Line 26: You want to exit out of the for loop once you find a match.

Line 29: You don't want to display this on each iteration through the loop. You want to move this statement to after line 32 and only display this if you've searched the entire array.

Thank you, how do i do what your saying in line 29 to 32?
It is working now but always shows the Sorry text.
It's best if you put lines 20-32 into a function.
1
2
3
4
5
6
7
8
9
10
11
bool FindMatch (string names[], string search, int cnt)
{   for (int j = 0; j<cnt; j++)
    {  if (names[j] == search)
        {    cout << "Congrats, the name is in the file!" << endl;
            return true;
        }     
    }
   // Match not found  
    cout << "Sorry, the name is NOT in the file." << endl;
    return false; 
}


Topic archived. No new replies allowed.