home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / c / other / learn / unget.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-12-03  |  1.2 KB  |  52 lines

  1. /* UNGET.C illustrates getting and ungetting characters from the console.
  2.  * Functions illustrated include:
  3.  *      getch           ungetch         putch
  4.  */
  5.  
  6. #include <conio.h>
  7. #include <stdio.h>
  8. #include <ctype.h>
  9.  
  10. void skiptodigit( void );
  11. int getnum( void );
  12.  
  13. main()
  14. {
  15.     int c, array[10];
  16.  
  17.     /* Get five numbers from console. Then display them. */
  18.     for( c = 0; c < 5; c++ )
  19.     {
  20.         skiptodigit();
  21.         array[c] = getnum();
  22.         printf( "\t" );
  23.     }
  24.     for( c  = 0; c < 5; c++ )
  25.         printf( "\n\r%d", array[c] );
  26.     printf( "\n" );
  27. }
  28.  
  29. /* Convert digit characters into a number until a non-digit is received. */
  30. int getnum()
  31. {
  32.     int ch, num =  0;
  33.  
  34.     while( isdigit( ch = getch() ) )
  35.     {
  36.         putch( ch );                        /* Display digit      */
  37.         num = (num * 10) + ch  - '0';       /* Convert to number  */
  38.     }
  39.     ungetch( ch );                          /* Put non-digit back */
  40.     return num;                             /* Return result      */
  41. }
  42.  
  43. /* Throw away non-digit characters. */
  44. void skiptodigit()
  45. {
  46.     int ch;
  47.  
  48.     while( !isdigit( ch = getch() ) )
  49.         ;
  50.     ungetch( ch );
  51. }
  52.