How to write own isnumber() function?

前端 未结 4 1267
我寻月下人不归
我寻月下人不归 2020-12-20 08:05

I\'m new to C and I\'m thinking how to write this function myself. I take a parameter from command line, so it is stored in argv array and I want to decide whether it is or

相关标签:
4条回答
  • 2020-12-20 08:16

    Read about strtol(3). You could use it as

    bool isnumber(const char*s) {
       char* e = NULL;
       (void) strtol(s, &e, 0);
       return e != NULL && *e == (char)0;
    }
    

    but that is not very efficient (e.g. for a string with a million of digits) since the useless conversion will be made.

    But in fact, you often care about the value of that number, so you would call strtol in your program argument processing (of argv argument to main) and care about the result of strtol that is the actual value of the number.

    You use the fact that strtol can update (thru its third argument) a pointer to the end of the number in the parsed string. If that end pointer does not become the end of the string the conversion somehow failed.

    E.g.

    int main (int argc, char**argv) {
       long num = 0;
       char* endp = NULL;
       if (argc < 2) 
         { fprintf(stderr, "missing program argument\n");
           exit (EXIT_FAILURE); }; 
       num = strtol (argv[1], endp);
       if (endp == NULL || *endp != (char)0)
         { fprintf(stderr, "program argument %s is bad number\n", argv[1]);
           exit (EXIT_FAILURE); }; 
       if (num<0 || num>=128)
         { fprintf(stderr, "number %ld is out of bounds.\n", num);
           exit(EXIT_FAILURE); };
       do_something_with_number (num);
       exit (EXIT_SUCCESS);
     } 
    
    0 讨论(0)
  • 2020-12-20 08:30

    How about trying like this:

    #include <ctype.h>
    
    if(isdigit(input))
    {
      return true;
    }
    else
    {
      return false;
    }
    

    OR more simple as H2CO3 commented:

     #define isnumber isdigit
    

    OR

    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    int main () {
    
      //some code
      theChar = atoi(string[i]);
      if (isdigit(theChar)) {
        return true;
      }
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-20 08:35

    I'm not sure if you want to check if it's a number or a digit and argv[1] is of type char * not int so you should do something like that:

    bool isDigit(char *param)
    {   
        return (*param >= `0` && *param <= `9`)
    }
    
    bool isNumber(char *param)
    {   
        while (param)
        {
            if (!isDigit(param))
                return false;
           param++;
        }
        return true;
    } 
    
    0 讨论(0)
  • 2020-12-20 08:39

    How about

    #define MYISNUM(x) ((x) >= '0' && (x) <= '9')
    
    0 讨论(0)
提交回复
热议问题