Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
984 views
in Technique[技术] by (71.8m points)

c - How to write own isnumber() function?

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 isn't number. What is the easiest way to do this?

Thank you

#include <stdio.h>

int isNumber(int *param)
{   
    if (*param > 0 && *param < 128)
        return 1;
    return 0;
} 

int main(int argc, char *argv[])
{
    if (argc == 2)
        isNumber(argv[1]);
    else printf("Not enought parameters.");

    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
");
       exit (EXIT_FAILURE); }; 
   num = strtol (argv[1], endp);
   if (endp == NULL || *endp != (char)0)
     { fprintf(stderr, "program argument %s is bad number
", argv[1]);
       exit (EXIT_FAILURE); }; 
   if (num<0 || num>=128)
     { fprintf(stderr, "number %ld is out of bounds.
", num);
       exit(EXIT_FAILURE); };
   do_something_with_number (num);
   exit (EXIT_SUCCESS);
 } 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...