C:检查命令行参数是否为整数?

2024-01-03

签名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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C:检查命令行参数是否为整数? 的相关文章

随机推荐