的签名是数字
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: 检查命令行参数是否为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29248585/