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.
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;
returntrue;
}
}
// Match not found
cout << "Sorry, the name is NOT in the file." << endl;
returnfalse;
}