Assigning Values to Structure Members

Employee clerk;             // clerk is an Employee

strcpy(clerk.firstName, "Ian");  // char array (string)
strcpy(clerk.lastName, "Faith"); // char array (string)
clerk.middleInitial = 'Q';       // char
clerk.salary = 45200.50f;        // float
clerk.age = 31;                  // int
clerk.years = 7;                 // int
This is what the structure looks like in memory now:
     clerk.firstName ®  I  a  n  0  ?  ?  ?  ?  ?  ?
      clerk.lastName ®  F  a  i  t  h  ?  ?  ?  ?  ?  ?  ?
 clerk.middleInitial ®  Q
        clerk.salary ®  45200.50
           clerk.age ®  31
         clerk.years ®  7
You can also initialize the structure in much the same way you initialize arrays:
Employee clerk = {"Ian", "Faith", 'Q', 45200.50f, 31, 7};
To assign values to a structure using cin, you can assign only one member at a time:
cin >> clerk.firstName;       // get a string
cin >> clerk.lastName;        // get a string
cin >> clerk.middleInitial;   // get a char
cin >> clerk.salary;          // get a float
cin >> clerk.age;             // get an int
cin >> clerk.years;           // get an int
You can't do this:
cin >> clerk;      // error, can't get a struct
Previous page
Next page

Back to Lesson 14 Index
Back to Outline