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);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…