home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C by Discovery (4th Edition)
/
C_By_Discovery_4th_Edition.tar
/
C_By_Discovery_4th_Edition
/
_DISK_
/
ch7
/
unions.c
< prev
Wrap
C/C++ Source or Header
|
2005-06-16
|
3KB
|
102 lines
/* unions.c
*
* Synopsis - Accepts input of and displays information for
* one employee.
*
* Objective - To demonstrate use of enum types to keep track
* of the contents of a union.
*/
/* Include Files */
#include <stdio.h>
#include <stdlib.h>
/* Constant Definitions */
#define NAME_LGTH 20
#define SSN_LGTH 12
#define BUF_LGTH 80
/* Type Descriptions */
enum paytype { hourly, salaried }; /* Note 1 */
union rate { /* Note 2 */
double per_hour;
int per_week;
};
struct employee {
char name[NAME_LGTH];
char ssn[SSN_LGTH];
enum paytype paytype; /* Note 3 */
union rate payrate;
};
/* Function Prototypes */
void reademp( struct employee *emptr );
/* PRECONDITION: emptr contains the address of a struct employee.
* POSTCONDITION: Accepts input information from the keyboard and
* stores it in a struct employee.
*/
void printemp( struct employee emp );
/* PRECONDITION: emp is a struct employee.
* POSTCONDITION: Displays the contents of the struct employee
* parameter.
*/
int main( void )
{
struct employee emp;
reademp( &emp );
printemp( emp );
return 0;
}
/*******************************reademp()***********************/
void reademp( struct employee *emptr )
{
char instring[BUF_LGTH];
printf( "Enter the information for an employee.\n" );
printf( "Name : " );
fgets( emptr->name, NAME_LGTH, stdin );
emptr->name[ strlen(emptr->name)-1 ] = '\0';
printf( "Social Security Number: " );
fgets( emptr->ssn, SSN_LGTH, stdin );
emptr->ssn[ strlen(emptr->ssn)-1 ] = '\0';
printf( "Hourly or salaried (h or s) : " );
fgets( instring, BUF_LGTH, stdin );
/* Note 4 */
if ( ( *instring == 'h' ) || ( *instring == 'H' ) )
emptr->paytype = hourly;
else if ( ( *instring == 's' ) || ( *instring == 'S' ) )
emptr->paytype = salaried;
else {
printf( "Illegal paytype, program terminated.\n" );
exit( 1 ); /* Note 5 */
}
if ( emptr->paytype == hourly ) { /* Note 6 */
printf( "Enter the hourly rate: " );
fgets( instring, BUF_LGTH, stdin );
emptr->payrate.per_hour = atof( instring );
}
else {
printf( "Enter the weekly salary: " );
fgets( instring, BUF_LGTH, stdin );
emptr->payrate.per_week = atoi( instring );
}
}
/*******************************printemp()**********************/
void printemp( struct employee emp )
{
printf( "Name : %s\n", emp.name );
printf( "Social Sec. No. : %s\n", emp.ssn );
if ( emp.paytype == hourly ) /* Note 7 */
printf( "Hourly rate :$%7.2f\n", emp.payrate.per_hour );
else
printf( "Weekly Salary :$%7d\n", emp.payrate.per_week);
}