Note: this will treat the string as though there are no other characters in the string other than numbers, so if the string was "1a3", it would return 13.
Edit: Now it also works with negative numbers, so if you had "-q1a3", it would return -13
Code: Select all
int stringToInt(string str)
{
int x = 0;
for(int i = str.size() - 1, j = 1; i >= 0; --i)
{
char current = str[i];
if(current >= '0' && current <= '9')
{
if(x < 0)
x = abs(x);
int y = (int)current - '0';
x += y * j;
j *= 10;
}
else if(current == '-')
x *= -1;
}
return x;
}
Edit2: I made a char* version:
Code: Select all
int stringToInt(char str[])
{
int ret = 0, multiple = 1;
char* ptr;
for(ptr = str; *ptr; ++i)
{;
if(*ptr >= '0' && *ptr <= '9')
{
if(x < 0)
x *= -1;
int y = (int)(*ptr) - '0';
x += y * multiple;
multiple *= 10;
}
else if(*ptr == '-')
x *= -1;
}
return x;
}