I am trying to find out if there is an alternative way of converting string to integer in C.
I regularly pattern the following in my code.
char s[] =
You can code atoi() for fun:
int my_getnbr(char *str)
{
int result;
int puiss;
result = 0;
puiss = 1;
while (('-' == (*str)) || ((*str) == '+'))
{
if (*str == '-')
puiss = puiss * -1;
str++;
}
while ((*str >= '0') && (*str <= '9'))
{
result = (result * 10) + ((*str) - '0');
str++;
}
return (result * puiss);
}
You can also make it recursive, which can fold in 3 lines. =)