isdigit
的签名
int isdigit(int c);
atoi
的签名int atoi(const char *nptr);
我只是想检查传递的命令行参数是否是整数,这是C代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
if (argc == 1)
return -1;
printf ("Hai, you have executed the program : %s\n", argv[0]);
if (isdigit(atoi(argv[1])))
printf ("%s is a number\n", argv[1]);
else
printf ("%s is not a number\n", argv[1]);
return 0;
}
但是,当我传递有效数字时,输出结果与预期不符:
$ ./a.out 123
Hai, you have executed the program : ./a.out
123 is not a number
$ ./a.out add
Hai, you have executed the program : ./a.out
add is not a number
我无法弄清楚错误。
最佳答案
当您引用argv[1]
时,它引用包含值123
的字符数组。 isdigit
函数是为单个字符输入定义的。
因此,要处理这种情况,最好定义一个函数,如下所示:
bool isNumber(char number[])
{
int i = 0;
//checking for negative numbers
if (number[0] == '-')
i = 1;
for (; number[i] != 0; i++)
{
//if (number[i] > '9' || number[i] < '0')
if (!isdigit(number[i]))
return false;
}
return true;
}
关于c - C:检查命令行参数是否为整数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29248585/