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

  1. /*                             identchk.c
  2.  *
  3.  *   Synopsis  - Prompts for and accepts input of a potential
  4.  *               C identifier and reports whether the identifier
  5.  *               is legal or not.
  6.  *
  7.  *   Objective - To illustrate a use of strspn().
  8.  */
  9. /* Header Files */
  10. #include <stdio.h>
  11. #include <string.h>
  12.  
  13. /* Constant Definitions */
  14. #define ID_LGTH 80
  15. #define FALSE 0
  16. #define TRUE 1
  17.  
  18. /* Function Prototypes */
  19. int id_legal( char id[] );
  20. /* PRECONDITION:  id is a null-terminated string.
  21.  * POSTCONDITION: returns TRUE if id is a legal C identifier and
  22.  *                FALSE if not.
  23.  */
  24.  
  25. int main()
  26. {
  27.      char identifier[ID_LGTH];
  28.      int retval;
  29.  
  30.      printf( "Enter your identifier: ");
  31.      fgets( identifier, ID_LGTH, stdin );
  32.      identifier[ strlen( identifier ) -1 ] = '\0';           /* Note 1 */
  33.  
  34.      retval = id_legal( identifier );
  35.  
  36.      if ( retval == TRUE )
  37.           printf( "The identifier %s is legal\n", identifier );
  38.      else
  39.           printf( "%s is not a legal identifer.\n", identifier );
  40.  
  41.      return 0;
  42. }
  43.  
  44. int id_legal( char id[] )
  45. {
  46.      char *legal = "abcdefghijklmnopqrstuvwxyz"              /* Note  2 */
  47.                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  48.                    "0123456789_";
  49.      char *start = "abcdefghijklmnopqrstuvwxyz"              /* Note 3 */
  50.                    "_ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  51.                                                              /* Note 4 */
  52.      if ( strspn( id, start) >= 1 && strspn( id, legal ) == strlen( id ) )
  53.           return TRUE;
  54.      return FALSE;
  55. }
  56.  
  57.