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

How to search array of structs for a string(name) and return info for that string(name)?

本文关键字:字符串 返回 信息 名称 结构 数组 搜索      更新时间:2023-10-16

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

我该怎么解决这个问题?

有1000行信息看起来像这样:

114680858 19670607 Matilda Vincent MI

114930037 19471024 Desdemona Hanover ID

115550206 19790110 Xanadu Perlman ND

116520629 19630921亚历山大大厅SD

117050976 19301016 David Lamprey GA

119610646 19650202 Thomas Porlock IL

120330928 19621126 Cary Cartman 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);
}
//  ...

有两个数组。一个在main中,另一个则在read_file中。它们的名字相同,但尺寸不同。

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

更好的做法是,取消阵列并使用std::vector。它将是std::vector<employees>

编辑1:搜索数组
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 <<
}

否则,对于一个数组,您的循环将看起来像:

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

一个很好的改进是,这个搜索函数没有对大小进行硬编码。因此,您可以在不修改search函数的情况下将大小从10(在main中)更改为1000。

如果对容器进行排序,可以使用二进制搜索
参见:std::binary_search, std::find, std::lower_bound, std::upper_bound