【问题标题】:Checking if characters in a char array are integers | c script检查 char 数组中的字符是否为整数 |脚本
【发布时间】:2021-02-15 11:44:10
【问题描述】:

您好,我有以下代码。假设循环遍历字符串中的每个字符,如果字符串中的一个字符不是数字 (0-9)(没有 ascii 值 0-9),则退出循环。

    //check if opperands are positive ints not zero
    size_t i =  0;
    //iterate through characters in string until null
    while (argv[1][i] != '\0') {
            int c = argv[1][i];
            if(c >= 0 && c <= 9){
                    printf("True\n");
                    i++;
            }
            else {
                    printf("false\n");
                    return 1;
            }

    }

但是,假设循环正在遍历字符串 1234,它将返回 false,即使所有数字 ascii 值都在 1 和 9 之间。任何人都知道它为什么这样做,我认为这可能是什么用我的 if/else 语句。谢谢!

【问题讨论】:

标签: c integer ascii main


【解决方案1】:

数字字面量 0 和 9 与字符字面量 '0' 和 '9' 不同。您应该将if (c &gt;= 0 &amp;&amp; c &lt;= 9) 替换为if (c &gt;= '0' &amp;&amp; c &lt;= '9')。注意数字周围的单引号。

【讨论】:

  • 这是因为我比较它们的 ascii 值是字符串吗?
  • @NatalieLloyd 不,他们是角色。字符需要用单引号括起来('0')。
  • 非常感谢
猜你喜欢
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-18
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
相关资源
最近更新 更多