Structures in C++
A structure is a data type which stores different data types and is created by the user. A struct keyword is used to define a structure. It is followed by the name of the structure and curly braces which contains the structure members. The members of the structure is accessed by dot operator using structure variable.
The following program shows a structure Student containing structure members str, age and marks of type string, integer and float. Structure variable s1 and s2 are used to access structure members using dot operator(.). The output is printed on the screen.
#include<iostream>
using namespace std;
struct Student { //Structure defination
string str;
int age;
float marks;
};
int main () {
Student s1, s2; //Structure variables s1 and s2
//Student1
cout<<"Enter the name of student ";
cin>>s1.str;
cout<<"Enter the age of student ";
cin>>s1.age;
cout<<"Enter the marks of the student ";
cin>>s1.marks;
//Student2
cout<<"\nEnter the name of student ";
cin>>s2.str;
cout<<"Enter the age of student ";
cin>>s2.age;
cout<<"Enter the marks of the student ";
cin>>s2.marks;
//Printing the details of students s1 and s2
cout<<"\nThe name of the student s1 is "<<s1.str<<endl;
cout<<"The age of the student s1 is "<<s1.age<<endl;
cout<<"The marks of the student s1 is "<<s1.marks<<endl;
cout<<"\nThe name of the student s2 is "<<s2.str<<endl;
cout<<"The age of the student s2 is "<<s2.age<<endl;
cout<<"The marks of the student s2 is "<<s2.marks;
return 0;
}
Output:
Enter the name of student xyz
Enter the age of student 19
Enter the marks of the student 88.25
Enter the name of student pqr
Enter the age of student 20
Enter the marks of the student 92.75
The name of the student s1 is xyz
The age of the student s1 is 19
The marks of the student s1 is 88.25
The name of the student s2 is pqr
The age of the student s2 is 20
The marks of the student s2 is 92.75