C++ Program to Store Information of an Employee in Structure

  • Write a C++ program to store data of an Employee in a structure variable.

In this C++ program, we will store the information of an Employee in a structure variable and then display it in screen. We want to store following information for an employee Name, Salary, Employee Code and Department. Here is a sample employee record :

Name : Jason Donald
Salary : 53463
Employee Code : 1234
Department : CSE

To store the information of employee, we will define an Employee structure containing all required information of employee.

struct Employee {
    char name[50];
    int salary;
    int employeeCode;
    char dept[5];
};

Then we will create a variable of Employee structure, let's say emp. Then to access the members of emp, we will use member access operator or dot(.) operator.

C++ Program to Store Information of an Employee in a Structure

// C++ program to store data of an employee in a structure variable
#include <iostream>
using namespace std;

struct Employee {
    char name[50];
    int salary;
    int employeeCode;
    char dept[5];
};

int main() {
    Employee e;
    
    cout << "Enter name of employee : ";
    cin.getline(e.name, 50);
    cout << "Enter department : ";
    cin.getline(e.dept, 5);
    cout << "Enter salary of employee : ";
    cin >> e.salary;
    cout << "Enter employee code : ";
    cin >> e.employeeCode;
    
    // Printing employee details 
    cout << "\n*** Employee Details ***" << endl;
    cout << "Name : " << e.name << endl << "Salary : " << e.salary << endl;
    cout << "Employee Code : " << e.employeeCode << endl << "Department : " << e.dept;
    return 0;
}
Output
Enter name of employee : Jason Donald
Enter department : CSE
Enter salary of employee : 53463
Enter employee code : 1234

*** Employee Details ***
Name : Jason Donald
Salary : 53463
Employee Code : 1234
Department : CSE

In above program, we first declare a variable of type Employee as

Employee e;
Then we ask user to enter details of employee i.e Name, department, salary and department and store it in corresponding fields of structure variable e.Finally we print the information of variable e on screen using cout.


Points to remember about Structures in C++
  • Structure in C++ programming language is a user defined data type that groups logically related information of different data types into a single unit.
  • Keyword struct is used to declare a structure.
  • We can declare any number of member variables inside a structure.
  • We can access the member of structure either using dot operator(.) or arrow operator(->) in case of structure pointer.