0

我正在做一个学校项目来搜索字符串数组,用户输入一些字符来搜索数组,并显示包含这些字符的全名和数字。这是可行的,但是当我询问用户是否要再次搜索时,程序会返回数组的全部内容。这是我的代码:

#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;
}

我无法弄清楚为什么会这样,请帮忙。

4

1 回答 1

0

添加

cin.ignore();

第 43 行和第 44 行之间修复了该错误。看这里的原因。

您应该尝试在不添加此行的情况下修复您的程序。

于 2021-11-15T00:46:35.107 回答