问题
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;
}
回答1:
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);
}
回答2:
How about
#define MYISNUM(x) ((x) >= '0' && (x) <= '9')
回答3:
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;
}
回答4:
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;
}
来源:https://stackoverflow.com/questions/19206660/how-to-write-own-isnumber-function