Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Searching an array of strings, getting weird return

I am doing a school project to search through an array of strings, where the user enters some characters to search through the array, and is displayed the full name and number that includes those characters. This is working, but when I ask if user wants to search again, the program returns the entire contents of the array. Here is my code:

#include <string>
#include <iostream>
using namespace std;

void findPerson(string, string[], int);

int main(){

const int SIZE = 12;
string searchIn;

string names[SIZE]
{
    "Matthew McConaughey, 867-5309",

    "Renee Javens, 678-1223",

    "Joe Looney, 586-0097",

    "Geri Palmer, 223-8787",

    "Lynn Presnell, 887-1212",

    "Bill Wolfe, 223-8878",

    "Sam Wiggins, 486-0998",

    "Bob Kain, 586-8712"

    "Tim Haynes, 586-7676"

    "John Johnson, 223-9037",

    "Jean James, 678-4939",

    "Ron Palmer, 486-2783"
};

char again = 'Y';

while (toupper(again) == 'Y')
{
    cout << "Please enter all or part of a name or number to search: " << endl;
    getline(cin, searchIn);

    findPerson(searchIn, names, SIZE);
    cin >> again;
    cout << endl;
}
return 0;
}

void findPerson(string finder, string myArray[], int size) {

bool found = false;

for (int index = 0; index < size; index++) {

    if (myArray[index].find(finder) != -1)
    {
        cout << myArray[index] << endl;
        found = true;
    }
}
if (!found)
    cout << "Nothing matched your search." << endl;

cout << "Would you like to search again? (Y/N): " << endl;
}

I cannot figure out why this is happening, please help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Adding

cin.ignore();

Between line 43 and 44 fixes the bug. See the reason why here.

You should try to fix your program without adding this line.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading