I try to convert a string to an integer by using this function:
#include <stdio.h>
#include <assert.h>
#include <limits.h>
int StringToInteger(const char* str) {
int sign = 1, result = 0;
assert(str != NULL);
while (*str == ' ' || *str == '\t' || *str == '\n' ||
*str == '\r' || *str == '\v' || *str == '\f') {
str++;
}
if (*str == '+') {
str++;
} else if (*str == '-') {
sign = -1;
str++;
}
while (*str >= '0' && *str <= '9') {
if (result > (INT_MAX / 10) || (result == INT_MAX / 10 && *str - '0' > (INT_MAX % 10))) {
return (sign == 1) ? INT_MAX : INT_MIN;
}
result = result * 10 + (*str - '0');
str++;
}
return result * sign;
}
For some reason, when it gets the following string 5240157683pykjw
it fails. How can I fix this?
For some reason it keeps iterating when encountering a non digit.