/* This program demonstrates * 1. Nested Structs * 2. Dynamic Struct variables * 3. Arrays of Structs * * This program also demonstrates advanced struct concepts * 1. Structs can contain arrays as data elements * 2. Structs can be nested - ie structs can contain other struct variables * 3. structs can by declared in dynamic memory and accessed through pointers */ #include #include #include using namespace std; // We use the same structs from last class struct Date { int month, day, year; char dayOfWeek[15]; }; /* Student structure * name - string * major - string * GPA - float * EMPL - long * grades - array of 3 floats * datOfBirth - Date struct variable */ struct Student { string name, major; float gpa; long empl; float grades[3]; Date dateOfBirth; }; // If a function uses a structure, it has to be declared after the struct declaration // We use the same functions from last class void printDate(Date d); Date readDate(); void printStudent(Student s); void readStudent( Student &s); int main() { /* We can use the new keyword to create a dynamic struct variable */ Student *st1 = new Student; // We can use the same functions, but we would need to dereference to match // the function signature. readStudent(*st1); cout<<"Student Details:\n"; printStudent(*st1); /* The Arrow Operator: We use the dot operator to access the data element of an struct * variable. * If we have a pointer to a struct variable instead, we need to use the arrow operator (->), * as shown below: */ cout<name <<" is "<< 2021 - st1->dateOfBirth.year << " years old"<>n; for(int i=0; i>num; Student *sPtr = new Student [num]; for(int i=0; i< num; i++) { cin.ignore(); // Remove the preceding newline readStudent(sPtr[i]); // use same as previous array } sum =0; /* Calculating class average for this array - same logic as before */ for(int i=0; i>var.month>> junk>> var.day>>junk>>var.year; return var; } /* This function accepts a structure variable and prints out the details in the structure * We use the dot (.) operator to access individual elements. */ void printStudent( Student s) { cout<>s.gpa; cout<<"EMPLID: "; cin>>s.empl; cout<<"3 grades: "; for(int i=0; i<3;i++) cin>>s.grades[i]; cout<<"Date of birth (Day of Week, m/d/y): "; cin.getline(s.dateOfBirth.dayOfWeek, 15, ','); cin>>s.dateOfBirth.month; cin.ignore(); cin>>s.dateOfBirth.day; cin.ignore(); cin>>s.dateOfBirth.year; }