我正在尝试创建一个允许我输入名称并返回结构中找到的员工信息的函数。 / ................................................. ......................
// info (ss_number,etc..)
struct employees {
int ss_number;
int dob; //date of birth
string f_name;
string l_name;
string state;
};
void print_person(employees e)
{
cout<<e.ss_number<<" "<<e.dob<<" "e.f_name<<" "<<e.l_name<<" "<<e.state;
}
void search(employees array[])
{
string first;
string last;
cout << "Enter name"; //Example Jack Patton
cin >> first >> last;
for(int i = 0; i < 10; i++) {
if(array[i].f_name == first && array[i].l_name == last) {
print_person(array[i]);
}
}
}
void main()
{
employees array[10];
search(array);
}
答案 0 :(得分:0)
这需要C ++ 11并满足您的要求。注意我切换到矢量(因为你正在使用你正在使用C ++的字符串),并且正在使用带有lambda的内置算法。 C ++在标准库中有许多内置功能,可以使这类事情变得更加容易。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Employee
{
int socialSecurtyNumber;
int yearOfBirth;
string firstName;
string lastName;
string state;
};
vector<Employee>::iterator search(vector<Employee> &employees, const string &first, const string &last)
{
return find_if(begin(employees), end(employees), [&](const Employee& employee){
return employee.firstName == first && employee.lastName == last;
});
}
int main()
{
vector<Employee> employees{
{ 100, 1985, "John", "Edwards", "AB" },
{ 101, 1960, "Mike", "Thomas", "CA" },
{ 102, 1992, "George", "Flunky", "FL" },
{ 103, 1983, "Tweet", "Johnson", "AB" },
{ 104, 1968, "Michael", "Jordan", "OH" },
};
string first;
string last;
cout << "Enter name: "; //Example Jack Patton
cin >> first >> last;
auto employee = search(employees, first, last);
if (employee != end(employees)){
cout << "FOUND! SSN: " << employee->socialSecurtyNumber << " YOB: " << employee->yearOfBirth << endl;
}else{
cout << "NOT FOUND!" << endl;
}
}
答案 1 :(得分:0)
* t最好将名称请求放在函数之外。该功能应该只进行搜索。
可以通过以下方式定义
const employee * search( const employees array[], size_t n,
const std::pair<std::string, std::string> &name )
{
const employees *first = array;
while ( first != array + n &&
!( first->f_name == name.first && first->l_name == name.second ) )
{
++first;
}
return first;
}
在main中它可以通过以下方式调用(考虑到main应该有返回类型int):
int main()
{
const size_t N = 10;
employees array[N];
// filling the array
std::pair<std::string, std::string> name;
cout << "Enter name"; //Example Jack Patton
cin >> name.first >> name.second;
const employees *emp = search( array, N, name );
if ( emp != array + N )
{
print_person( *emp );
}
//...
}
或者您可以将标准算法std::find_if
与谓词一起使用。
同时,函数print_person应定义为
void print_person( const employees &e)
{
cout<<e.ss_number<<" "<<e.dob<<" "e.f_name<<" "<<e.l_name<<" "<<e.state;
}
答案 2 :(得分:0)
除了您从未为数组初始化任何值之外,您所拥有的内容几乎没有问题。
您可以从文件中读取它们,但在此期间写下它并且它将起作用(感谢M2tM获取数据):
employees array[10] =
{ { 100, 1985, "John", "Edwards", "AB" }
, { 101, 1960, "Mike", "Thomas", "CA" }
/* fill in more rows if you want */
};
其他问题:在print_person
<<
之前,您错过了e.f_name
; void main()
应为int main()
。