Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use | Resource CD

Initializing Structure Variables

CAUTION: While it is possible to initialize structure variables by using a "list", this method does not apply when the structure uses apvector, apmatrix, or apstring.
point

struct TREE_TYPE
{
     int month;
     int day;
     int year;
};

int main(void)
{
     TREE_TYPE treePlanted = { 04, 02, 1980 }; //filling by list
     TREE_TYPE treeHarvested = { 06, 11, 2001 };
     . . . 

 

As with all variables, structures can be filled by assignment, with user input, or from a file.  Notice how the dot (.) operator is used to reference each member of the structure in the examples below:

By Assignment: By User Input:
. . .
struct STUDENT_TYPE
{
     apstring name, street, city, state, zip; 
     int age;
     double IDnum;
     double grade;
} ;

int main(void)
{
     // Declare a struct
     STUDENT_TYPE student1;

     // initialize the members of the struct
     student1.name = '"Garfield";
     student1.street = "123 Mouse Lane";
     student1.city = "Catsville";
     student1.state = "PAW";
     student1.zip = "12345";
     student1.age = 3;
     student1.IDnum = 101010101;
     student1.grade = 98.5;
     . . .

 

struct STUDENT_TYPE
{
     apstring name, street, city, state, zip; 
     int age;
     double IDnum;
     double grade;
} ;

int main(void)
{
     // Declare an array of structs
     apvector<STUDENT_TYPE> roster(10);

     // fill the array of structs
     for (int i = 0; i<10; i++)
     {
          cout<<"Please enter info "
                 <<"for student "<<i+1<<endl;
          cout<<"Enter the name: ";
          getline(cin, roster[ i ].name );
          …
         cout<"Enter the age: ";
         cin>> roster[ i ].age;
         . . .





It is possible to use a structure to define another structure, thus creating "nested" structures :

struct ADDRESS_TYPE
{
     apstring street, city, zipcode;
};

struct STUDENT_TYPE
{
     apstring name;
     ADDRESS_TYPE address;
     int age;
     double IDnum;
     double grade;
};