Recently I had a interview from MS, I had a requirement to write a function to implement string to int. At the moment I did not make the function perfect, after the interview, i finalized the function as following.
int meatoi(const char * src)
{
if (src == 0 || *src =='/0') {cout<<"error"; return INT_MAX;}
char *temp =const_cast<char*>(src);
int returnvalue=0;
int length = strlen(temp);
bool negtive = false;
while(*temp !='/0')
{
if(length ==strlen(src) && (*temp == '-'))
{
negtive = true;
--length;
++temp;
continue;
}
--length;
if(*temp >='0' and *temp <='9')
{
int value = *temp - '0';
value *=static_cast<int>(pow(10.0,length));
returnvalue +=value;
++temp;
}
else {
throw string("error input");
}
}
if(negtive) { returnvalue = ~returnvalue +1;}
return returnvalue;
}