How to write own isnumber() function?

拈花ヽ惹草 提交于 2019-11-29 12:34:40

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);
 } 

How about

#define MYISNUM(x) ((x) >= '0' && (x) <= '9')

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;
}

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;
} 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!