/* ** validB.c ** checking the validity of a given string as an acceptable identifier in C ** (binary search used) ** -- written by Jeff Tian, 11/17/98. */ #include #include #include #define MaxKeywords 32 #define MaxKeywordLength 12 char get_input(void); void ignore_line(void); int IsValidName(char *name); int IsLiteral(char *name); int IsKeywordB(char *name); static char keywords[MaxKeywords][MaxKeywordLength] = { "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "int", "long", "register", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while" }; main() { char c, vname[32]; printf("This program checks variable/function/constant names for validity.\n"); c = get_input(); while (c == 'y' || c == 'Y') { printf("Please enter a name: "); if (IsValidName(vname)) printf("\"%s\" .... is a valid name.\n", vname); c = get_input(); } } /* ** get_input() -- query user for continuation and get user input */ char get_input(void) { char c; printf("\nWould you like to continue [y/n]? "); while(isspace(c = getchar())); ignore_line(); return(c); } /* ** ignore_line() -- ignore all the input until '\n' */ void ignore_line(void) { while (getchar() != '\n'); } /* ** IsValidName() -- check validity of names */ int IsValidName(char *vname) { if (!IsLiteral(vname) ) return(0); if (IsKeywordB(vname) ) return(0); return(1); } /* ** IsLiteral() -- check validity of and store alpha-numerical literals */ int IsLiteral(char *name) { char c; int answer=1, i=0; while(isspace(c = getchar())); if (!isalpha(c) && c != '_') { printf("Illegal name: illegal leading character \'%c\'.\n", c); answer = 0; } name[i++] = c; c = getchar(); while (answer && !isspace(c) ) { if (!isalpha(c) && c != '_' && !isdigit(c)) { printf("Illegal name: illegal trailing character \'%c\'.\n", c); answer = 0; } else if (i >= 30) { printf("Illegal name: string too long.\n"); answer = 0; } else { name[i++] = c; c = getchar(); } } if (c != '\n') ignore_line(); name[i] = '\0'; return(answer); } /* ** IsKeywordB() -- check if a given name is a keyword, using binary search */ int IsKeywordB(char *name) { int i=0, iskywd=0, done=0, lwbd=0, upbd=MaxKeywords-1, order; while (!iskywd && !done) { if (upbd <= lwbd) { done = 1; } else { i = lwbd + (upbd - lwbd) / 2; order = strcmp(keywords[i], name); if (order == 0) { printf("Illegal name: keyword \"%s\" used.\n", name); iskywd = 1; } else if (order < 0) { lwbd = i+1; } else { upbd = i-1; } } } return(iskywd); }