In this article, you’ll learn about how to make a C++ Program to read & print an employee’s details using structure with explanation.
What is Structure in C++?
Structure is a collection of variables of different data types under a single name. It is similar to a class in that, both holds a collection of data of different data types. For example: You want to store some information about a person: his/her name, citizenship number and salary
C++ Program to read & print an employee’s details using structure
#include <iostream>
using namespace std;
struct Employee {
string name;
int age;
string job_title;
float salary;
};
int main() {
Employee emp;
// Read employee details
cout << "Enter name: ";
getline(cin, emp.name);
cout << "Enter age: ";
cin >> emp.age;
cout << "Enter job title: ";
cin.ignore(); // clear the input buffer
getline(cin, emp.job_title);
cout << "Enter salary: ";
cin >> emp.salary;
// Print employee details
cout << "\nEmployee Details:" << endl;
cout << "Name: " << emp.name << endl;
cout << "Age: " << emp.age << endl;
cout << "Job Title: " << emp.job_title << endl;
cout << "Salary: " << emp.salary << endl;
return 0;
}
Explanation
- We start by defining a structure called “Employee”. This structure has four members: name, age, job_title, and salary. These members are of different data types – string, int, string, and float, respectively.
- Inside the main function, we declare a variable “emp” of type Employee. This variable will hold the employee’s details that we will read from the user.
- We use the “cout” statement to prompt the user to enter the employee’s details. Then, we use the “getline” and “cin” functions to read the user input and store it in the corresponding members of the “emp” variable.
- After reading the employee’s details, we use the “cout” statement again to print the details back to the user. We access the members of the “emp” variable using the dot (.) operator.
- Finally, we return 0 to indicate that the program has completed successfully.
Note: In order to read a string with spaces using “getline”, we need to clear the input buffer before using it. We can do this by using the “cin.ignore()” function.
Output
The output of the program will depend on the user input. Here’s an example of the program’s output for some sample input.
Enter name: John Doe
Enter age: 32
Enter job title: Software Engineer
Enter salary: 60000
Employee Details:
Name: John Doe
Age: 32
Job Title: Software Engineer
Salary: 60000
In this example, the user entered the name “John Doe”, age 32, job title “Software Engineer”, and salary 60000. The program then printed these details back to the user.