Monday, July 27, 2009

Convert string to integer in C, without using atoi function?

Basically, I want to know what's "behind" atoi... A site which explains/expands functions in C would be useful, too.

Convert string to integer in C, without using atoi function?
Here is the simplest example. It's a bit clumsy as it doesn't check for overflow:





int my_atoi ( const char * s )


{


int n = 0;


if(!s) return 0;


while(*s)


{


if(*s%26lt;'0' || *s%26gt;'9')


return 0;


n = n * 10 + *s - '0';


s++;


}


return n;


}
Reply:just substract each character by '0'


No comments:

Post a Comment