自定义库函数:atoi和itoa
#include <iostream>
using namespace std;
int atoi(char* s)
{
if(s == NULL)
{
cout<<"Invalid Input"<<endl;
return -1;
}
while(*s == ' ') // 去掉开头空格
s++;
int sign = (*s == '-')?-1:1;
if(*s == '-')s++; // 跳过符号位
int result = 0;
while(*s >= '0' && *s <= '9')
{
result = result*10 + (*s - '0');
s++;
}
while(*s == ' ') // 去掉末尾的空格
s++;
if(*s != '\0')
{
cout<<"Invalid Input"<<endl;
return -1;
}
return result*sign;
}
/*---------------------------------------*/
char* itoa(int num, char* str, int base)
{
char* ptr = str;
int sign = num;
if(sign < 0)
num = -num;
while(num)
{
*ptr++ = num%base + '0';
num = num/base + '0';
if(num < base)
{
*ptr++ = num + '0';
break;
}
if(sign < 0) *ptr++ = '-';
*ptr = '\0';
int j = ptr - str - 1; //获取转换后的字符数,不包含'\0'
for(int i = 0; i<j;i++, j--) // 首尾互换
{
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
return str;
}
}
网友评论