Code /* * demostruct2.cpp * demonstration usage of struct * - nested structs * - an array of structs * CIS 250 * David Klick * 2005-01-24 * */ #include #include #include using std::strcpy; struct date { int month; int day; int year; }; struct emptype { char lastname[15]; unsigned long id; double rate; date hiredate; }; void printemp(emptype e); void setfields(emptype&, char*, unsigned long, double, int, int, int); int main(void) { emptype emp[5]; // set members of emp array setfields(emp[0], "Smithson", 1786, 32.00, 3, 3, 1996); setfields(emp[1], "Guimond", 3654, 17.95, 4, 2, 2004); setfields(emp[2], "Crenshaw", 9812, 14.00, 11, 1, 2000); setfields(emp[3], "Lovitz", 17543, 27.25, 7, 10, 1999); // use assignment operator to set last array element emp[4] = emp[0]; // display all the array elements for (int i=0; i<5; i++) { printemp(emp[i]); } return 0; } void printemp(emptype e) { using std::cout; using std::endl; using std::setw; using std::setfill; using std::showpoint; using std::setprecision; using std::setiosflags; using std::ios; using std::fixed; cout << setw(15) << e.lastname << " ID=" << setfill('0') << setiosflags(ios::fixed | ios::scientific) << setprecision(6) << setw(6) << e.id << setfill(' ') << " rate=$" << setw(6) << fixed << showpoint << setprecision(2) << e.rate << " hired=" << setw(2) << setfill('0') << e.hiredate.month << "/" << setw(2) << e.hiredate.day << '/' << setw(2) << (e.hiredate.year % 100) << setfill(' ') << endl; } void setfields(emptype& e, char* nm, unsigned long id, double hrate, int m, int d, int y) { strcpy(e.lastname, nm); e.id = id; e.rate = hrate; e.hiredate.month = m; e.hiredate.day = d; e.hiredate.year = y; } /* Sample output: Smithson ID=001786 rate=$ 32.00 hired=03/03/96 Guimond ID=003654 rate=$ 17.95 hired=04/02/04 Crenshaw ID=009812 rate=$ 14.00 hired=11/01/00 Lovitz ID=017543 rate=$ 27.25 hired=07/10/99 Smithson ID=001786 rate=$ 32.00 hired=03/03/96 */