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

标签 c command-line

的签名是数字

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/

相关文章:

c - 为什么这个C程序会显示这个结果?

c - 如何将字符串指针转换为 64 位(_int64)变量?

c - 这个 gcc 编译器命令中的 -z 选项是什么?

windows - 使用批处理脚本重命名文件

C/C++ 以编程方式获取空闲内存

c - 如何从c中的标准输入读取长度未知的字符流

cygwin下调用winapi编译链接静态库

c - 处理异常的strcpy和strcat的实现

command-line - 将灰度图像转换为具有可定义阈值的 1 位黑白图像,并保持透明度?

java - 处理文件目录