This is the question my teacher gave me:
Employee
that consists of the following fields:
ID
, name
, degree
, age
Employee
type), fills it from the user the, then returns it.Employee
type) and prints its fields.I tried to solve it although I didn't understand it and this is what I have, Pleas help:
struct Employee
{
int ID;
char name[10];
char degree;
int age;
};
int fillin()
{ Employee employee;
cout<<"Enter employee ID, NAME, DEGREE and AGE:\n";
cin>>employee.ID;
cin>>employee.name;
cin>>employee.degree;
cin>>employee.age;
}
int print()
{
Employee employee;
cout<<"ID: "<< employee.ID<<" , ";
cout<<"NAME: "<< employee.name<<" , ";
cout<<"Degree: "<< employee.degree<<" , ";
cout<<"AGE: "<< employee.age<<".\n ";
}
int main()
{
int num;
cout<<"Enter number of employees: ";
cin>> num;
string *name= new string[num];
for(int i = 0; i < num;i++)
{
name[i]=fillin();
}
for(int j : name){
print();
}
return 0;
}
A function can have parameters and return a value. So here, fillin
should return an Employee
object, and print
should take an Employee
(or better a const reference) parameter:
Employee fillin()
{ Employee employee;
cout<<"Enter employee ID, NAME, DEGREE and AGE:\n";
cin>>employee.ID;
cin>>employee.name;
cin>>employee.degree;
cin>>employee.age;
return employee; // return the local object
}
void print(const Employee& employee)
{
cout<<"ID: "<< employee.ID<<" , ";
cout<<"NAME: "<< employee.name<<" , ";
cout<<"Degree: "<< employee.degree<<" , ";
cout<<"AGE: "<< employee.age<<".\n ";
}
Your main function could become:
int main()
{
int num;
cout<<"Enter number of employees: ";
cin>> num;
Employee *name= new Employee[num];
for(int i = 0; i < num;i++)
{
name[i]=fillin();
}
for(int i=0; i<num; i++){
print(name[i]);
}
return 0;
}
Of course, you should check that the input methods return valid values (check cin
after each read)