c - how to check whether a inputted value is a character or not -


so working on mastermind game , whenever inputs string, freaks.

    //invalids if (space1!='a' && space1!='b' && space1!='c' && space1!='d' && space1!='e' && space1!='f')     {     printf("invalid entry.\n");     goto label;     } if (space2!='a' && space2!='b' && space2!='c' && space2!='d' && space2!='e' && space2!='f')     {     printf("invalid entry.\n");     goto label;     } if (space3!='a' && space3!='b' && space3!='c' && space3!='d' && space3!='e' && space3!='f')     {     printf("invalid entry.\n");     goto label;     } if (space4!='a' && space4!='b' && space4!='c' && space4!='d' && space4!='e' && space4!='f')     {     printf("invalid entry.\n");     goto label;     } 

separate validation logic own function. can take advantage of strchr function in standard library particular test:

int isvalid( int c )  {   static const char *validchars = "abcdef";   return strchr( c, validchars ) != null; } 

if value of c 1 of characters in validchars, strchr return pointer character, otherwise return null. if c not 1 of a, b, c, d, e, or f, isvalid function return 0 (false), otherwise return 1 (true).

now, assuming spacen variables separate inputs, not part of same input. simplest (if not intuitive) approach guarantee single-character input following:

char c; if ( scanf( " %c%*[^\n]", &c ) == 1 ) // note leading blank in format string!   // valid single-character input 

this tell scanf skip on leading whitespace (including newlines), read , store first non-whitespace character c, , consume but not store next newline.

note - anytime find creating bunch of variables of same type same name , ordinal space1, space2, space3, space4, you're better off using array.

putting together, get:

int space[4];   /**  * number of elements in space array; way  * don't have hardcode size in our loop  */ size_t numelements = sizeof space / sizeof space[0];  ( = 0; < numelements; i++ ) {   int done = 0;     {     printf( "gimme input (0 quit): " );     fflush( stdout );     if ( scanf( " %c%*[^\n]", &space[i] ) != 1 )     {       fprintf( stderr, "error reading input, bailing...\n" );       exit( 0 );     }     done = isvalid( space[i] );     if ( !done && space[i] != '0' )       fprintf( stderr, "invalid input, try again\n" );   } while ( !done && space[i] != '0' );    if ( space[i] == '0' )   {     fprintf( stderr, "got '0' input, quitting...\n" );     exit( 0 );   } } 

without seeing more of code, don't know if useful or not.


Comments