The problem seems to be with the fact that you have passed an array by value to the function
void setContainer(string x[], int size).
That means that the operations going on inside this function are being performed on a copy of your array instead of on the "container" array you created in Main(). You aren't actually adding the strings to variable "container".
Not sure if you are comfortably with the standard template library, but there are a ton of useful containers there that could help with this type of operation. Using, say a std::set container, you can reduce the need for some of those loops in your code; they are also much easier to pass either by reference or by value. Here's what it would look like using std::set.
#include <iostream>
#include <string>
#include <set> // so we can use std::set
usingnamespace std;
void setContainer(set<string>& container, int size) // pass a set of strings instead of an array
{
string x;
for (int i = 0; i < size; i++) {
cout << "Please enter strings you want to array: ";
cin >> x;
container.insert(x);
}
}
string containerChecker(const set<string>& container, string x)
{
set<string>::const_iterator const_iter;
const_iter = container.find(x); // set is a binary search tree that makes it easy to find stuff.
if (const_iter == container.end())
return"Not Found";
return *const_iter;
}
int main()
{
set<string> container; // make container a std::set object.
string checker = "";
setContainer(container, 5);
cout << "What string would you like to check? ";
cin >> checker;
string confirm = containerChecker(container, checker);
if (confirm != "Not found") {
cout << "The search have found, the word: " << "|" << confirm << "|";
}
else
cout << "Not found";
return 0;
}
@tNK, the logic in function containerChecker is wrong. You should only return "Not found" AFTER you have checked ALL possibilities (i.e. after the end of the for loop). There will be no "else" here.
Change your lines 27 - 29 from
1 2 3
elsereturn"Not found";
}
to
1 2 3
} // end of for loop
return"Not found";
Maybe you want to reconsider your code though. Since the most you are going to do with containerChecker is echo back the word you sent it, it seems more natural that this function should simply return a bool: true (if found) and false (if not found).
Using, say a std::set container, you can reduce the need for some of those loops in your code; they are also much easier to pass either by reference or by value.
Since, the order strings are stored here does not matter std::unordered_set can be used. If order is not needed it is usually best to use it instead of std::set. There may also be improved performance (though in this case not much).