如何在结构数组中搜索字符串(名称)并返回该字符串(名称)的信息?

问题描述 投票:0回答:2

使用此程序,当我输入名称时,不会返回任何内容。

我该如何解决?

有1000条信息,看起来像这样:

114680858 19670607 Matilda Vincent MI

114930037 19471024汉诺威Desdemona ID

115550206 19790110 Xanadu Perlman ND

116520629 19630921亚历山大·霍尔SD

117050976 19301016 David Lamprey GA

119610646 19650202 Thomas Porlock IL

120330928 19621126卡里·卡特曼NC

等......

代码:

struct employees
{
    int ss_number;//social security
    int dob;//date of birth YYYY/MM/DD Ex.) 19870314=1987/03/14
    string f_name;
    string l_name;
    string state; //state of residence
};

void read_file()//read file into array of 1000 structs
{
    ifstream data("/home/www/class/een118/labs/database1.txt");
    employees array[1000]
    if(!data.fail())
    {
        int i;
        for(int i=0;i<1000;i++)
        {
            data>>array[i].ss_number
                >>array[i].dob
                >>array[i].f_name
                >>array[i].l_name
                >>array[i].state;
        }
        for(int i=0;i<1000;i++)
        {
            cout<<array[i].ss_number>>" "<<array[i].dob>>" "<<array[i].f_name>>" "<<
            array[i].l_name>>" "<<array[i].state;
        }
    }
}

void print_person(employees e)
{
    cout<<e.ss_number>>" "<<e.dob>>" "<<e.f_name>>" "<<e.l_name>>" "<<e.state;
}

void search(employees array[])//type in name and get that persons ss_number,dob etc...
{
    string first;
    string last;
    cout<<"Enter name";
    cin>>first>>last;
    for(int i=0;i<1000;i++)
    {
        if(array[i].f_name==first && array[i].l_name==last)
        {
            print_person(array[i]);
        }
    }
}

void main()
{
    employees array[10];
    read_file();
    search(array);
}
//  ...
c++ arrays string struct
2个回答
0
投票

search函数中,您不应使用相等比较

if (array[i].f_name==first)

您应使用std::string::compare

std::string::compare

这将以您期望if (array[i].f_name.compare(first) == 0) 的相同方式返回True。


0
投票

有两个数组。一个在==中,另一个在main中。它们具有相同的名称,但大小不同。

read_file中的数组与read_file中的数组没有关系。您将数组传递给了main,但没有传递给search。我建议您通过引用将数组传递给read_file,并删除read_file中的数组声明。

更好的是,消除阵列并使用read_file。它将是std::vector

编辑1:搜索数组std::vector<employees>函数中,您将需要传递两个附加参数:数组容量和数组中的记录数。如果使用search,则可以通过以下方式获取数组中的雇员数:

std::vector<employees>

number_of_employees = array.size(); 循环将使用迭代器:

for

否则,使用数组,您的循环将看起来像:

std::vector<employees>::const_iterator iter;
for (iter = array.begin(); iter != array.end(); ++iter)
{
  // process array slot by dereferencing it:
    employee e = *iter;
    cout << e << "\n"; // This could happen if you overloaded operator <<
}

一个很好的改进是,此搜索功能不会对大小进行硬编码。因此,您可以将大小从10(在void search(employees array[], unsigned int capacity, unsigned int employees_in_array) { for (unsigned int i = 0; i < employees_in_array; ++i) { cout << array[i]; } } 中)更改为1000,而无需修改main功能。

如果对容器进行排序,则可以使用二进制搜索。参见:search

© www.soinside.com 2019 - 2024. All rights reserved.