| by Arround The Web | No comments

Initialize struct in C++

In programming, we frequently encounter circumstances where we want to store a collection of data, whether they are of relevant or irrelevant datatypes. In C++, we already know about arrays, which are used to hold collections of information of relevant datatypes in adjacent memory addresses. But in structures, we can store the user-defined datatypes, they can be different datatypes or can be relevant datatypes. Structures carry a group of variables that have different datatypes but under one identifier which is “struct”. The “struct” is the reserved keyword in C++ language and a short form of structures that are used to develop the structures in the program. Let us just examine the syntax of Structures to gain a better understanding of the idea of structures and how we’re going to initialize them inside the C++ programming language.

Syntax:

The following is the syntax for structures that can hold many types of variables. The syntax in the C++ programming language relates to both the style in which code is written and how variables are defined in a C++ structure implementation. Understanding the syntax is very important since the C++ programming language is case-sensitive. The translator would throw a syntax error if we unintentionally declared the variables or datatypes wrong. To implement the structures, we first write the “struct” keyword which is used to develop structure in the program.

Next, we will declare the name of the structure which we used in the program to access the structures. Then, we open the structure brace and we will create multiple variables of different data types. In the end, the “;” sign has been utilized to complete the structure after the closing brace.

Example 01:

Let us start implementing the simplest and most basic example of structures in C++ programming language. For the use of standardized functions in C++, we are going to include the necessary packages so that we can easily access the functions. The “iostream” library, which is used to collect user input and display the results in user terminal windows, is represented by the header file that we are including. There is a specified method for importing libraries in C++ programs. First, we write the “#” symbol to notify the compiler that we are retrieving the library. Next, we write the reserved keyword “include” to tell the compiler that we are now incorporating the package into the program. The name of the library we are implementing is “iostream,” which will be written between the “<>” tokens.

The “namespace std” directive will be written next, which will prevent the compiler from granting the same scope to additional variables, functions, classes, etc. Line 4 will mark the beginning of the driver code, which will be used to implement the program’s main problem. To begin writing the code, open the brackets after calling the main() function.

#include <iostream>    
using namespace std;

int main()
{    
    struct Triangle      
    {      
        int base, height;      
    };

    Triangle tri;  
   
    tri.base=15;    
    tri.height=10;  
   
    float area = (tri.base * tri.height) / 2;
    cout << "Area of Triangle is: " << area << endl;    
    return 0;    
}

 
First, we will create the structure inside the main() function which starts with the keyword “struct” and then we will write the name of the structure named “Triangle”. Inside the structure braces, we have declared two variables named “base” and “height” of integer type. Then, we have terminated the structure with the “;” sign. After creating the structure, we want to access the structure members, so we have created an object “tri” of Triangle type. We assigned the values to the “triangle” members and concatenated them with the object “tri”. In line 16, we have initialized another variable “area” of float type and we have stored the formula of the triangle in it. We want to display the area of the triangle so we have passed “area” in the cout() method.

Example 02:

Here is another slightly different example of Structures in which we are going to initialize the structure outside the main() function. We have included the header file and namespace directive so that we can easily employ the built-in methods in the existing program.

#include <iostream>
using namespace std;

struct student
{
    char name[30];
    int id;
    string department;
    string semester;
    float marks;
};

int main()
{
    cout << "*-----Please Enter  Valid Student Information-----*" << endl;
    student stu;
   
    cout << "\nEnter Full Name: ";
    cin.get(stu.name, 30);
    cout << "Enter Registration: ";
    cin >> stu.id;
    cout << "Enter Department: ";
    cin >> stu.department;    
    cout << "Enter Semester: ";
    cin >> stu.semester;
    cout << "Enter Total Semester Marks: ";
    cin >> stu.marks;

    cout << "\n\n*-----Academic Information of " << stu.name << "-----*"<< endl;
   
    cout << "\nName: " << stu.name << endl;
    cout <<"Reg No: " << stu.id << endl;
    cout <<"Department: " << stu.department << endl;
    cout << "Semester: " << stu.semester << endl;
    cout << "Total Marks: " << stu.marks;
    return 0;
}

 
Next, we initialized a structure named “student” by writing the “struct” keyword first. To declare the members of the structure, we open the left curly brace “(“ of the structure. We have declared 5 members of the structure with different datatypes of the variables. The first variable is the “name” of type “char” and we have also assigned a maximum length to the name is 30. Then, the second member is “id” of type “int”. The third and the fourth variable members are different which are “department” and “semester” but the datatypes are the same which is “string” and the last member is “marks” of type float.

To close and terminate the structure “student”, we will use the right curly brace “)” with the termination sign “;” at the end of the structure. After initializing the structure, let us move on to the main() function and start writing the drivers code of the program. First, we have to write the message in double quotation marks in the cout() statement which we want to display in the user console window. In Line 16, we have created an object “stu” of the structure “student” which we have already created outside the main() function so that we can easily access the structure members. Then, we used the cout() and cin() statements one by one to get the information from the user and store it in the “struct” members.

After getting the information related to the student, we want to display all the information to the user. So, we have first printed another message that tells the user that we are displaying the academic result of the student with the student’s name in the title. Then, we called the cout() method and we passed the structure object “stu” concatenated with the member name of the student one by one. To end the implementation of the program, we have used the “return” keyword with 0. This will tell the compiler that the program has successfully executed without generating any type of error.

Conclusion

In this tutorial, we have come to know how we can initialize the structure in the C++ programming language. We have learned what is the role of structures and why we used them in the programming language. We have also implemented the structure inside and outside the main() function so that we can learn different initialization techniques of the structures.

Share Button

Source: linuxhint.com

Leave a Reply