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).
//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. Thanks!
The number literal 0 and 9 are not the same as the character literal '0' and '9'. You should replace if (c >= 0 && c <= 9)
with if (c >= '0' && c <= '9')
. Note the single quotes around the digits.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.