|
|
|
|
|
|
|
Just as we can read values into specific components of an array, we can read values into members of a struct. The statement |
|
|
|
|
|
|
|
|
cin >> student.finalExam; |
|
|
|
|
|
|
|
|
reads a value from the standard input device and stores the value into the finalExam member of student. As with arrays, we cannot read in an entire struct as an aggregate; we must read values into a struct one member at a time. |
|
|
|
|
|
|
|
|
An alternative to reading in values is to initialize a struct in its declaration. The syntax is similar to the initialization of an array: you provide a list of initial values, separate the values with commas, and enclose the whole list within braces. Here's an example of declaring and initializing the variable student: |
|
|
|
|
|
|
|
|
StudentRec student =
{
John,
Smith,
3.24,
320,
290,
95,
B
}; |
|
|
|
|
|
|
|
|
We have formatted the initializer list vertically but could just as well have arranged it horizontally. Each value in the initializer list corresponds to one member of the struct. The two strings are stored into the firstName and lastName members, 3.24 is stored into the gpa member, 320 is stored into the programGrade member, and so forth. |
|
|
|
|
|
|
|
|
The struct component student.lastName is an array. We can access the individual elements in this component just as we would access the elements of any other array: we give the name of the array followed by the index, which is enclosed in brackets. |
|
|
|
|
|