如何在结构数组中搜索字符串(名称)并返回该字符串的信息
How to search array of structs for a string(name) and return info for that string(name)?
使用此程序,当我键入名称时,不会返回任何内容。
我该怎么解决这个问题?
有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
- C 字符串返回字符串的整数/双精度/长整型值
- std::hash<std::string> 可以为不同的字符串返回相同的值吗?
- Java 调用 dll 字符串返回类型方法
- 返回具有C++字符串返回值的函数的本地 C 字符串
- 如何将两个 jlong 数据类型转换为 jstring,然后将两个字符串连接在一起以便从 JNI 将字符串返回给 jav
- 尝试以随机字符(长读取)打印字符串返回结果
- 从字符串返回 i(索引)字
- 函数读取最大和min int值,并用文本字符串返回
- 如何将 YAML 节点中的序列作为字符串返回?
- 将注册表项读取为字符串返回数值
- 为什么我在尝试打印字符串返回时收到编译器错误?
- 使用 char*array 存储条形图的条形图,以便我可以动态制作它并作为字符串返回
- 字符串返回功能不起作用 - 'identifier is underfined'
- 将C 本地字符串返回到另一个功能
- 在MATLAB中仅接受INT32PTR时,将错误编号作为字符串返回
- 字符串流到字符串返回
- 字符串返回错误的长度
- 从共享指针矢量字符串返回值
- C++随机字符串返回意外结果
- 临时标准::字符串返回垃圾