签名 isdigit
int isdigit(int c);
Run Code Online (Sandbox Code Playgroud)
签名 atoi
int atoi(const char *nptr);
Run Code Online (Sandbox Code Playgroud)
我只是想检查传递的命令行参数是否是整数.这是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;
}
Run Code Online (Sandbox Code Playgroud)
但是当我传递一个有效数字时,输出并不像预期的那样:
$ ./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
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚错误.
niy*_*asc 13
引用时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;
}
Run Code Online (Sandbox Code Playgroud)
R S*_*ahu 12
if (isdigit(atoi(argv[1])))
Run Code Online (Sandbox Code Playgroud)
将会:
if (isdigit(atoi("123")))
Run Code Online (Sandbox Code Playgroud)
这将是:
if (isdigit(123))
Run Code Online (Sandbox Code Playgroud)
这将是:
if ( 0 )
Run Code Online (Sandbox Code Playgroud)
因为123代表ASCII字符'{'.
| 归档时间: |
|
| 查看次数: |
33694 次 |
| 最近记录: |