Saturday, December 8, 2018
Home > C++ > Structure in C++

Arrays are used to combine several data items of the same kind but w the at if we want to combine data items of a different kind. To solve this issue C++ allows us to create user-defined data types known as structures in which we can combine data items of a different kind.
In C++ a structure is defined using the following syntax:

struct  structure-Name
{
// here you can define any number of data items.
};


Data items
that can be defined inside a structure can be any of the data types in c++ or user-defined data type.
struct is the reserved word to define structures.
structure-Name can be any name following the same rules as for a variable name.
E.g.

struct student {
int id;
string name;
float cgpa;
};

The above definition of the structure will define a structure named the student. This structure is combining three different data types as can be seen in its definition.

How to Access Members of a Structure?

To access members of a structure we need to make an object of the structure which is then used to access each member of a structure with dot (.) operator.


struct student {
int id;
string name;
float cgpa;
};

In main function we need to make, an object for the student as:


student std;
std.id;
std.name;
std.cgpa;

E.g.

#include "stdafx.h"
#include"iostream"
#include"string"

using namespace std;

struct student 
{
     int id;
     string name;
     float cgpa;
};

int main()
{
     student std;
     cout << "***Input in User Defined data Type***" << endl;
     cout << "Please Enter Id for Student : ";
     cin >> std.id;
     cin.ignore();// this is used to ignore any garbage value from previous input.
     cout << "Please Enter name for Student : ";
     getline(cin, std.name);
     cout << "Please Enter CGPA for Student : ";
     cin >> std.cgpa;
     cout << "***Output in User Defined data Type***" << endl;
     cout << "Id for Student is :" << std.id << endl;
     cout << "Name for Student is :" << std.name << endl;
     cout << "CGPA for Student is :" << std.cgpa << endl;
}

Output: –
structure - C++ struct

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: