The search function works, and it will find what I'm searching for. The problem is that if I have 5 objects in my vector and search for the last one, the 'else' statement is shown 4 times before it finds the object.
Also if the object I'm searching for is in the first spot, the else statement will run 4 times after I press enter.
This is telling the user the object he or she is searching for exists. And then the program changes its mind and tells it's not present.
Please, how can I make the 'else' statement to run ONLY if the object is NOT present?
If the function should end after the element has been found you could place a return statement instead of a break; on line 12. That will prevent the code after the loop from running.
Otherwise you will have to place the code inside an if statement that only runs if the element was not found. You could do that by setting a boolean variable to false before the loop starts and set it to true if the element was found. After the loop you check the boolean variable and run the code only if it is false.
string Foo;
getline(cin, Foo);
vector<string>::iterator it;
for(it = Bar.begin();it<Bar.end();it++)
{
if(it->Foobar == Foo)
{
cout << Foo << " is available. Press <ENTER> to continue." << endl;
cin.get();
break;
}
}
// if "Foo" was not found then "it" will now point to "Bar.end()"
if (it == Bar.end())
{
cout << Foo << " is not available. Please try again." << endl;
cout << "\nPress <ENTER> to continue." << endl;
cin.get();
}