C:检查命令行参数是否为整数? [英] C: Checking command line argument is integer or not?

查看:88
本文介绍了C:检查命令行参数是否为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

isdigit的签名

int isdigit(int c);

atoi

int atoi(const char *nptr);

我只是想检查传递的命令行参数是否为整数,这里是C代码:

I just wanted to check whether the command line argument passed was an integer or not.Here is the C Code:

#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;
}

但是,当我传递有效数字时,输出结果与预期不符:

But the output is not as expected, when I am passing a valid number:

$ ./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 函数是为单个字符输入定义的。


因此,要处理这种情况,最好按以下方式定义一个函数:

When you refer argv[1], it refers to a character array containing value 123. isdigit function is defined for a single character input.

So to handle with this situation, it is better to define a function as follows:

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:检查命令行参数是否为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆