Wierd problem with search in vector

I have a search function wich matches a user input string value with one of the variables on my objects placed in a vector. This works just fine:


EXAMPLE:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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;
    }

    else
    {
        cout << Foo << " is not available. Please try again." << endl;
        cout << "\nPress <ENTER> to continue." << endl;
        cin.get();
        break;
    }
}


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?

Thanks in advance
Put the else part after the loop.

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.
Yeah what peter87 told is right.
You can do it like .

int x = 0;

for(it = Bar.begin();it<Bar.end();it++)
{
if(it->Foobar == Foo)

{ x = 1;
break;
}


}


if (x == 1)
{
number found
}
else
{
number not found
}
I simply forgot the '==' operator and used '=', thats why it did not work.

Now it is working! Thank you!!!
Last edited on
You used = instead of == on line 21.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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();
}


@tntxtnt

Thank you, much more simple
Topic archived. No new replies allowed.