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

时间:2015-03-25 06:08:32

标签: c command-line

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

我无法弄清楚错误。

6 个答案:

答案 0 :(得分:12)

当您引用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;
}

答案 1 :(得分:12)

if (isdigit(atoi(argv[1]))) 

将是:

if (isdigit(atoi("123")))

将是:

if (isdigit(123))

将是:

if ( 0 )

因为123代表ASCII字符'{'

答案 2 :(得分:1)

我以为我会在这里添加一些答案。除了检查基数10中的数字之外,我认为检查并允许十六进制数字也是有用的。我也允许负数。

我还添加了一些东西来检查输入错误(例如空指针,表示十进制数字的字符串内的字母,或表示十六进制数字的字符串内的无效字母)。

请注意,我使用to_lower(char c)函数确保代表十六进制的字母为小写,仅为方便起见。

如果字符串是有效数字,则返回1(或true),如果不是,则返回0。如果它是有效数字,我将基数存储在参数库中。

// Return 1 if str is a number, 0 otherwise.
// If str is a number, store the base (10 or 16) in param base.
static int is_number(char *str, int *base)
{
    // Check for null pointer.
    if (str == NULL)
        return 0;

    int i;
    int len = strlen(str);

    // Single character case.
    if (len == 1)
    {
        *base = 10;
        return isdigit(str[0]);
    }

    // Hexadecimal? At this point, we know length is at least 2.
    if ((str[0] == '0') && (str[1] == 'x'))
    {
        // Check that every character is a digit or a,b,c,d,e, or f.
        for (i = 2; i < len; i++)
        {
            char c = str[i];
            c = to_lower(c);
            if (!(
                (c >= '0' && c <= '9') || 
                (c >= 'a' && c <= 'f')))
                return 0;
        }
        *base = 16;
    }
    // It's decimal.
    else
    {
        i = 0;
        // Accept signs.
        if (str[0] == '-' || str[0] == '+')
            i = 1;

        // Check that every character is a digit.
        for (; i < len; i++)
        {
            if (!isdigit(str[i]))
                return 0;
        }
        *base = 10;
    }
    return 1;
}

我使用了这个函数:

int base, num;
if (is_number(str, &base)
    num = strtol(str, NULL, base);

答案 3 :(得分:0)

我不知道isdigit究竟做了什么,但由于名称,我认为它应该采用char参数,检查字母是否为数字,是吗?

我会这样写:(省略了函数shell,只显示核心代码)

char* p = argv[1];
while (*p != '\0')
{
    if (*p<'0' || *p>'9')
    {
        printf("%s is not a number", argv[1]);
        return 0;
    }
    p++;
}
printf("%s is a number", argv[1]);
return 0;

答案 4 :(得分:0)

isdigit()函数检查数字字符(&#39; 0&#39;到&#39; 9&#39;)当然这取决于ASCII值。现在,从你的atoi返回的值不属于&#39; 0&#39;之间的ASCII值。到&#39; 9&#39;所以它表明它不是一个数字。

答案 5 :(得分:-1)

// Since There is an implicit conversion from const char* to std::string
// You May use this simplified version of the check_string instead

     bool isNumeric(const string str) 
    {
        // loop Through each character in the string
        for(char x:  str)
            if(!isdigit(x)) // Check if a single character "x" its a digit
            return false;  // if its not return false 

      return true; // else return true
    }  
相关问题