Search code examples
c++arraysdynamic-arrays

how can I print dynamic array in c++ I need explanation to this question


This is the question my teacher gave me:

  • Construct a structure Employee that consists of the following fields: ID, name, degree, age
  • A function that creates an object (a variable of Employee type), fills it from the user the, then returns it.
  • A function that receives an object (a variable of Employee type) and prints its fields.
  • Inside the main function:
    • Ask the user to specify the number of employees.
    • Create a dynamic array of the size specified by the user for the employees.
    • Inside a loop, fill the array elements one at a time by calling the first function.
    • Inside another loop, print the array elements one at a time by calling the second function.

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

Solution

  • 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)