Skip to main content

Thread: (C) - A program to see if a variable name is valid


hi -
i've written following code meant find out if variable name valid. name valid if starts either letter or underscore, , (after that) contains alphanumeric characters or underscores.
however, code giving warning , note, , segfaults when run it.
code:
     /* public domain - see if variable */   /* name valid.  */      #include <stdio.h>  #include <stdlib.h>   #include <string.h>  #include <ctype.h>      /* helper function test underscore.  */   int isuscore(char ch)    {      return ( ch == '_') ;   }       /* see if string valid name.  */   void validname(char *str)   {      if ( isalpha(str[0]) || isuscore(str[0]) )  str++ ;           else puts("bad first character! \n");       if ( isalnum(str) || isuscore(str) )  str++ ;             else puts("found char other alnum or underscore! \n");               puts("this valid name. \n");    }       int main() {     char *str1 = "_1test" ;   /* valid */   char *str2 = "foo_42" ;   /* valid */   char *str3 = "5bar" ;     /* not valid */     validname(str1);   validname(str2);   validname(str3);            return 0;      }
i following when run code -
validname.c:35: warning: passing argument 1 of ‘isuscore’ makes integer pointer without cast
validname.c:18: note: expected ‘char’ argument of type ‘char *’

so, appreciated - i'm sure i'm close, not quite close enough.....
- trilobite

your code terribly hard read! if want make harder read, why not concatenate of lines of code make 1 large line? make sure embed semi-colon appropriate separate statements.

correct code issues, need pass single character ctype.h functions. also, better declare strings const char.

code:
...  /* see if string valid name.  */ void validname(const char* str) {    if (isalpha(*str) || isuscore(*str))    {       str++;    }    else    {       puts("bad first character! \n");       return;    }    if (isalnum(*str) || isuscore(*str))    {       str++;   /* needed??? */    }    else    {       puts("found char other alnum or underscore! \n");       return;    }     puts("this valid name. \n"); }   int main() {     const char* str1 = "_1test";  /* valid */    const char* str2 = "foo_42";  /* valid */    const char* str3 = "5bar";    /* not valid */  ...
p.s. prefer *str in lieu of str[0].

------------

edit:

test program using following, , fix code show not valid declaration:
code:
const char* str4 = "_5*foo";   /* not valid */
hint: use ispunct() , isspace() on entire range of characters in string. code looking @ first 2 characters.


Forum The Ubuntu Forum Community Ubuntu Specialised Support Development & Programming Programming Talk [SOLVED] (C) - A program to see if a variable name is valid


Ubuntu

Comments