J.Doe J.Doe - 12 days ago 5
C++ Question

C++ Print out "not found" message when searching a vector only once

here is a little snippet of my code where I am stuck. I want the code to keep prompting the user to search for a name, even when found. So breaks in my code won't work. My code is flawed because every time the for loop reaches one less my vector size it prints out "name not found!"
Which is what I told it, but I just can't figure out a way to fix this. I have found other posts on stack and tried them in my code but they are not working.

do
{
cout <<"Enter name for search: ";
cin >> name;

for (int i = 0; i < pvector.size(); i++)
{
if (pvector[i]->fName == name || pvector[i]->lName == name)
{
cout << pvector[i]->fName << " "<< pvector[i] ->lName <<" "<<"username:"<< pvector[i]->userName <<" "<<"password:" << pvector[i]->pword <<endl;
}else if(i == pvector.size()-1)
{
cout << name <<" "<<"not found!" << endl;
}
}
} while (cin.good());

Answer

You're missing a break once you've find a match, this works on my side:

#include "stdafx.h"

#include <iostream>
#include <vector>
#include <string>


using namespace std;

int main()
{
    std::vector<std::string> pvector;
    pvector.push_back("Steve");
    pvector.push_back("Jhon");
    pvector.push_back("Michael");

    char name[256];

    do
    {
        cout << "Enter name for search: ";
        cin >> name;

        for (int i = 0; i < pvector.size(); i++)
        {
            if (pvector[i] == name)
            {
                cout << pvector[i] << " found" << endl;
                break;
            }
            else if (i == pvector.size() - 1)
            {
                cout << name << " " << "not found!" << endl;
            }
        }
    } while (cin.good());
}