I need to write a function which will check a string for a few properties:
- The string must represent a positive integer (> 0)
- The integer mustn't require more than 32 bits of memory
- There are no letters in the string
If these conditions are met, it should return the string as an int, if any of these conditions are not met, it should return -1.
Currently the function fails to deal with the following 2 inputs:
4y
13.4
If my isDigit()
loop works as intended it'd be able to check for them. Why does the loop not work?
int convert(const char length[]) {
long input = atol(length);
if (input >= 2147483648 || input <= 0) {
return -1;
}
int chkr = 0;
while (chkr < strlen(length)) {
if (isdigit(length[chkr++]) == 0) {
return -1;
}
else {
return atoi(length);
}
}
input = atol(length);
if (length[0] == '0') {
return -1;
}
if (strlen(length) < 3) {
return -1;
}
else {
return atoi(len gth);
}
}