home *** CD-ROM | disk | FTP | other *** search
/ C by Discovery (4th Edition) / C_By_Discovery_4th_Edition.tar / C_By_Discovery_4th_Edition / _DISK_ / ch6 / switch2.c < prev   
C/C++ Source or Header  |  2005-06-16  |  2KB  |  75 lines

  1. /*               switch2.c
  2.  *
  3.  *   Synopsis  - Displays a menu, accepts a choice from a user,
  4.  *               and processes the response.
  5.  *   Objective - Illustrates the switch and break statements
  6.  *               together.
  7.  */
  8. /* Include Files */
  9. #include <stdio.h>
  10.  
  11. /* Constant Definitions */
  12. #define BUF_SIZE 40
  13.  
  14. /* Function Prototypes */
  15. void processresponse( char iochar );
  16. /*   PRECONDITION:  iochar can be any character value.
  17.  *
  18.  *   POSTCONDITION: Compares iochar with the case labels and takes 
  19.  *                  action accordingly.
  20.  */
  21.  
  22. int menu( void );
  23. /*   PRECONDITION:  none
  24.  *
  25.  *   POSTCONDITION: Displays the menu choices and accepts input of the 
  26.  *                  user's response. The first character of the 
  27.  *                  response is returned.
  28.  */
  29.  
  30. int main( void )
  31. {
  32.      char iochar = 0;
  33.      do {
  34.           iochar = menu();                        /* Note 1 */
  35.           processresponse( iochar );
  36.      }
  37.      while ( iochar != '0' );
  38.      return 0;
  39. }
  40.  
  41. /*******************************menu()**************************/ 
  42.  
  43. int menu( void )
  44. {
  45.      char response[BUF_SIZE];
  46.  
  47.      printf( "The following games are available:\n" );
  48.      printf( "----------------------------------\n\n" );
  49.      printf( "1. Guessit\n" );
  50.      printf( "2. Nim\n" );
  51.      printf( "----------\n" );
  52.      printf( "Choose a game or type 0 to exit.\nYour choice?  ");
  53.  
  54.      if ( fgets( response, BUF_SIZE, stdin ) == NULL )
  55.           return( '0' );                          /* Note 1 */
  56.      else
  57.           return( response[0] );                  /* Note 1 */
  58. }
  59.  
  60. /*******************************processresponse()***************/
  61.  
  62. void processresponse( char iochar )
  63. {
  64.      switch ( iochar ) {                          /* Note 2 */
  65.           case '0':  break;                       /* Note 3 */
  66.           case '1':  printf( "You have chosen guessit.\n" );
  67.                      break;                       /* Note 4 */
  68.           case '2':  printf( "You have chosen nim.\n" );
  69.                      break;                       /* Note 4 */
  70.                                                   /* Note 5 */
  71.            default:  printf( "Illegal input.\n" );
  72.                      printf( "Choose 0, 1, or 2.\n" );
  73.      }
  74. }
  75.