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

  1. /*               ctype.c
  2.  *
  3.  *   Synopsis  - Counts the number of alphabetics, digits,
  4.  *               whitespace, punctuation and control characters
  5.  *               in its input. The input can come from a file
  6.  *               or the keyboard.
  7.  *
  8.  *   Objective - To illustrate the use of the functions defined
  9.  *               in ctype.h.
  10.  */
  11. /* Include Files */
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <ctype.h>                                  /* Note 1 */
  15.  
  16. int main( int argc, char *argv[] )
  17. {
  18.      FILE *fp;
  19.      int ch;
  20.      int numlower = 0, numupper = 0, numdigit = 0,
  21.          numspace = 0, numcntrl = 0, numalpha = 0,
  22.          numpunct = 0;
  23.  
  24.      if ( argc < 2 )
  25.           fp = stdin;                               /* Note 2 */
  26.      else if (( fp = fopen( argv[1], "r" )) == NULL ) {
  27.           printf( "Can't open file %s.\n", argv[1] );
  28.           exit( 1 );
  29.      }
  30.  
  31.      while (( ch = getc( fp )) != EOF ) {
  32.           if ( isalpha( ch ))  {                    /* Note 3 */
  33.                numalpha++;
  34.                if ( islower( ch ))                  /* Note 4 */
  35.                     numlower++;
  36.                else
  37.                     numupper++;                     /* Note 5 */
  38.           }
  39.           else if ( isdigit( ch ))                  /* Note 6 */
  40.                numdigit++;
  41.           else if ( isspace( ch ))                  /* Note 7 */
  42.                numspace++;
  43.           else if ( ispunct( ch ))                  /* Note 8 */
  44.                numpunct++;
  45.           else if ( iscntrl( ch ))                  /* Note 9 */
  46.                numcntrl++;
  47.      }
  48.      printf( "\nThat data contained %d alphabetic characters ", numalpha );
  49.      printf("of which %d were uppercase \n", numupper );
  50.      printf( "and %d were lowercase.  It also contained ", numlower );
  51.      printf( "%d digits, %d whitespace", numdigit, numspace );
  52.      printf( "characters,\n%d control characters, ", numcntrl );
  53.      printf( "and %d punctuation characters.\n", numpunct );
  54.      return 0;
  55. }
  56.