简体   繁体   English

检查字符数组中的字符是否为整数 | 脚本

[英]Checking if characters in a char array are integers | c script

Hi I have the following code.嗨,我有以下代码。 It is suppose to loop through each character in the string and break out of the loop if one of the characters in the string is not a digit (0-9) (does not have ascii value 0-9).假设遍历字符串中的每个字符并在字符串中的一个字符不是数字 (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;
            }

    }

however, say the loop is iterating through the string 1234 it will return false, even though all of the digits ascii values are between 1 and 9. Anyone have any ideas on why it is doing this, I think it might be something with my if/else statement.但是,如果循环遍历字符串 1234,它将返回 false,即使所有的 ascii 数字值都在 1 到 9 之间。任何人都知道为什么要这样做,我认为这可能与我的 if /else 语句。 Thanks!谢谢!

The number literal 0 and 9 are not the same as the character literal '0' and '9'.数字字面量 0 和 9 与字符字面量“0”和“9”不同。 You should replace if (c >= 0 && c <= 9) with if (c >= '0' && c <= '9') .您应该将if (c >= 0 && c <= 9)替换为if (c >= '0' && c <= '9') Note the single quotes around the digits.注意数字周围的单引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM