Preparing Array of Structures
Program to demonstrate how an array of structures is prepared to get entry of multiple similar type of data entries.
Learning Objectives
- Preparing array of structures so that multiple instances of similar data records can be stored.
Source Code
|
Run Output
Code Understanding
struct Student { char name[60]; int marks;};
This structure can collect data of name and marks of Student.
Student s[3];
This is array of structures. Here for convenience sake we have taken just a size of 3. We can make as many students we like for such an array. We have created this array before main() so that even external functions out of main can also use it if desired. This is a global declaration.
for(int i=0;i<3;i++) //This loop is for filling structure array
{
cout<<“Enter Student Name : “; cin.getline(s[i].name,60);
Here we collect the name. For each instance of array we use the iteration count i and write as s[i].name. Here i begins from 0 so the array is correctly filled from index 0.
cout<<“Enter Marks out of 100: “; cin>>s[i].marks;
Similarly marks are also collected.
cin.ignore(100,’n’);
We use this as in second iteration onwards the newline character of marks entry has to be ignored. This is a requirement of cin.getline(). read more about this in code notes of #2781.
}
cout<<endl<<“Entered data is — “<<endl; //This is message before printing the data
for(int i=0;i<3;i++) { cout<<s[i].name<<“, “<<s[i].marks<<endl; }
Using this loop the data filled in previous loop is printed. Here again array index count is used.
Notes
- Array of structures is a good and simple technique to create database records type of entry. However the limitation of number of records is evident as the array size has to be fixed.
Common Errors
- Not using cin.ignore is the common error students do. Students may use gets() function of C, but it is generally not recommended as it can take unlimited string data and corrupt memory of nearby variables.
Suggested Filename(s): struarr.cpp
sunmitra| Created: 22-Jan-2018 | Updated: 19-Dec-2018|