atoi是将数字符号的字符串转化为整形。
itoa是将整形转化为字符串。
参考代码如下
void Reverse(char * start,char* end) { char *l = start; char *r = end; while (l < r) std::swap(*l++,*r--); } char *my_itoa( int value, char *str) { char* temp = str; int num = 0; int flag = 1; if (value < 0) //判断是否是负数 { flag = 0; value = -value; } while(value != 0) { num = value%10; *temp++ = num+'0'; value = value/10; } if(flag == 0) //将符号加上 *temp = '-'; else temp--; Reverse(str,temp++); //这时的字符串是逆着的,需要逆序 *temp = '\0'; //字符串结束标志 return str; }
int my_atoi( const char *str) { assert(str); int flag = 1; int num = 0; while ((*str) ==' ') //跳过空格 str++; if (*str== '-') //判断符号 { flag = 0; str++; } else if(*str == '+') str++; while (*str != '\0') { if ('0'<=*str && *str<='9') { num = num*10+*str-'0'; } else break; str++; } if(flag == 0) //判断是否是负数 num = -num; return num; }
测试代码如下:
int main() { int i = 0; i = atoi("12345"); cout<<i<<endl; i = my_atoi("12345"); cout<<i<<endl; i = atoi(" 12345"); cout<<i<<endl; i = my_atoi(" 12345"); cout<<i<<endl; i = atoi(" -12345"); cout<<i<<endl; i = my_atoi(" -12345"); cout<<i<<endl; i = atoi(" a12345"); cout<<i<<endl; i = my_atoi(" a12345"); cout<<i<<endl; i = atoi(" +12345"); cout<<i<<endl; i = my_atoi(" +12345"); cout<<i<<endl; i = atoi(" -u12345"); cout<<i<<endl; i = my_atoi(" -u12345"); cout<<i<<endl; i = atoi(" +012345"); cout<<i<<endl; i = my_atoi(" +012345"); cout<<i<<endl; i = atoi(" -01a345"); cout<<i<<endl; i = my_atoi(" -01a2345"); cout<<i<<endl; char a[7]; cout<<_itoa(65534,a,10); cout<<_itoa(-65534,a,10); std::cout<<my_itoa(65534,a); std::cout<<my_itoa(-65534,a); return 0; }
测试结果是:
![]()