Check if User Inputs a Letter or Number in C

后端 未结 7 1576
终归单人心
终归单人心 2020-12-03 15:22

Is there an easy way to call a C script to see if the user inputs a letter from the English alphabet? I\'m thinking something like this:

if (variable == a -          


        
7条回答
  •  没有蜡笔的小新
    2020-12-03 16:16

    The strto*() library functions come in handy here:

    #include 
    #include 
    #include 
    #define SIZE ...
    
    int main(void)
    {
      char buffer[SIZE];
      printf("Gimme an integer value: ");
      fflush(stdout);
      if (fgets(buffer, sizeof buffer, stdin))
      {
        long value;
        char *check;
        /**
         * strtol() scans the string and converts it to the equivalent 
         * integer value.  check will point to the first character
         * in the buffer that isn't part of a valid integer constant;
         * e.g., if you type in "12W", check will point to 'W'.  
         *
         * If check points to something other than whitespace or a 0
         * terminator, then the input string is not a valid integer. 
         */
        value = strtol(buffer, &check, 0);
        if (!isspace(*check) && *check != 0)
        {
          printf("%s is not a valid integer\n", buffer);
        }
      }
      return 0;
    }
    

提交回复
热议问题