这是两道经常考到的笔试题,看似简单的实现,其实专注到细节,还是有很多需要注意扣分的地方。
atoi实现:
1 #include <iostream> 2 #include<ctype.h> 3 using namespace std; 4 5 typedef enum status{ 6 OK,ERROR 7 }Status; 8 9 Status myErrno = ERROR; 10 int my_atoi(const char *p); 11 int main() 12 { 13 char *mystr = "45678910"; 14 int ret = my_atoi(mystr); 15 cout << ret << endl; 16 return 0; 17 } 18 19 //实现atoi函数,将字符串转换为数字 20 int my_atoi(const char *p){ 21 myErrno = ERROR; 22 if(NULL == p) 23 return 0; 24 25 int ret = 0; 26 27 const char *temp = p; 28 29 //判断如果是前几位为空格,则向前移动字符串位置 30 while(isspace(*temp)) 31 temp++; 32 33 //判断符号位,是否为负数 34 bool minus = *temp=='-' ? true : false; 35 36 //有符号位 37 if('+' == *temp || '-' == *temp) 38 ++temp; 39 40 while(*temp != '