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 / exit.c < prev    next >
C/C++ Source or Header  |  2005-06-16  |  2KB  |  63 lines

  1. /*               exit.c
  2.  *
  3.  *   Synopsis  - Reads a stream of digits for its input, converts
  4.  *               the input to an integer value, and displays it.
  5.  *               Finding a nondigit in input is an error.
  6.  *
  7.  *   Objective - To illustrate error handling with the exit()
  8.  *               library function.
  9.  */
  10.  
  11. /* Include Files */
  12. #include <stdio.h>
  13. #include <ctype.h>                                /* Note 1 */
  14. #include <stdlib.h>                               /* Note 2 */
  15.  
  16. /* Function Prototypes */
  17. int convert( void );
  18. /*   PRECONDITION:  none 
  19.  *
  20.  *   POSTCONDITION: Reads standard input until either a blank, an end 
  21.  *                  of line or a nondigit is found. If only digits are 
  22.  *                  found, the function returns the converted value as 
  23.  *                  type int. Otherwise, the function error() is 
  24.  *                  called.
  25.  */
  26.  
  27. void error( void );
  28. /*   PRECONDITION:  none
  29.  *
  30.  *   POSTCONDITION: Displays an error message and terminates the 
  31.  *                  program with exit value 1.
  32.  */
  33.  
  34. int main( void )
  35. {
  36.      printf( "Enter a positive integer > " );
  37.                                                   /* Note 3 */
  38.      printf( "The value entered was %d.\n", convert() );
  39.      exit( 0 );                                   /* Note 4 */
  40. }
  41.  
  42. /*******************************convert()***********************/
  43.  
  44. int convert( void )
  45. {
  46.      int  ch,
  47.           sum = 0;
  48.      while ((( ch = getchar() ) != ' ' )&& (ch != '\n' )) {
  49.  
  50.           if ( !isdigit( ch ) )                   /* Note 1 */
  51.                error();
  52.           sum = sum * 10 + ( ch - '0' );          /* Note 5 */
  53.      }
  54.      return ( sum );
  55. }
  56. /*******************************error()*************************/
  57.  
  58. void error( void )
  59. {
  60.      printf( "Nondigit in input. Program terminated.\n" );
  61.      exit( 1 );                                      /* Note 6 */
  62. }
  63.