-1

嗨,我有以下代码。假设循环遍历字符串中的每个字符,如果字符串中的一个字符不是数字 (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 语句。谢谢!

4

1 回答 1

2

数字字面量 0 和 9 与字符字面量 '0' 和 '9' 不同。您应该替换if (c >= 0 && c <= 9)if (c >= '0' && c <= '9'). 注意数字周围的单引号。

于 2020-11-02T19:23:27.490 回答