如何显示具有相同信息的多个项目

How to show multiple items with the same information?

本文关键字:信息 项目 何显示 显示      更新时间:2023-10-16

我正在编写一个程序,它可以显示来自学生列表的信息。我想知道我怎样才能使程序打印出所有共享相同信息的学生。例如:有两个学生都住在伦敦,当我输入"伦敦"时,程序只打印出它在列表中找到的第一个学生。下面是我当前的代码:

void Person_list::findAddr()
{
    Person *s;
    string addr;
    string temp_addr;
    s = head;
    cout << "Please enter student's address: ";
    getline(cin, addr);
    while ((s!=NULL) && (s-> Get_addr() != addr))
    {
        s = s -> next;
    }
    if (s != NULL)
    {
        s -> Show();
    }
    if (s == NULL)
    {
        cout << "Cant find. n" << endl;
    }
} 

你的问题是while循环的条件:

while ((s!=NULL) && (s-> Get_addr() != addr))

它说:只要s不为空,地址不是你要找的那个,看看下一个学生。

在第一次查找时,循环终止,因此后续可能的查找永远不会到达。

你可以这样做:

while (s != nullptr) {
    if (s-> Get_addr() == addr) {
        s -> Show();
    }
    s = s -> next;
}

遍历所有学生,只在地址匹配的情况下打印。