c/c++语言开发共享C:检查命令行参数是否为整数?

签名的isdigit

 int isdigit(int c); 

atoi签名

 int atoi(const char *nptr); 

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

 #include  #include  #include  int main(int argc, char *argv[]) { if (argc == 1) return -1; printf ("Hai, you have executed the program : %sn", argv[0]); if (isdigit(atoi(argv[1]))) printf ("%s is a numbern", argv[1]); else printf ("%s is not a numbern", 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; } 

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

    将会:

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

    这将是:

     if (isdigit(123)) 

    这将是:

     if ( 0 ) 

    因为123代表ASCII字符'{'

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

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

    请注意,我使用to_lower(char c)函数来确保表示hex的字母为小写,只是为了方便起见。

    如果字符串是有效数字,则返回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); 

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

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

    char* p = argv[1]; while (*p != '') { 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;

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

      以上就是c/c++开发分享C:检查命令行参数是否为整数?相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/544866.html

      (0)
      上一篇 2021年1月9日
      下一篇 2021年1月9日

      精彩推荐