int atoi (const char * str); //Convert string to integer
char * itoa ( int value, char * str, int base ); //Convert integer to string (non-standard function)
#include <stdio.h>
#include <ctype.h>
int my_atoi(const char *s)
{
int i =0;
int total = 0;
int sign;
while(isspace(*s)) //跳过空白符
s++;
sign = *s;
if(*s == '+' || *s == '-') //跳过符号位
{
s++;
}
while(isdigit(*s))
{
total = 10*total + (*s - '0'); //将数字字符转换成整形数字
s++;
}
if(sign == '-')
return -total;
else
return total;
}
int main(void)
{
char str[256];
printf ("Enter your a numeric string: ");
scanf("%s",str);
printf("%d\n",my_atoi(str));
}
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
char *my_itoa(int value, char * str, int base)
{
int sign,ch;
int i,len;
char *tmp = str;
char c;
unsigned uvalue;
if(base > 36 || base <=1)
{
printf("Base is between 2 and 36\n");
return 0;
}
sign = (base == 10 && value < 0);
if(sign) //记录符号,使value为正数
uvalue = -value;
else
uvalue = (unsigned)value;
while(uvalue)
{
ch = uvalue%base;
uvalue = uvalue/base;
if(ch < 10)
*tmp = ch + '0'; // 0-9 直接输出"0"-"9"
else
*tmp = ch - 10 + 'a'; // > 10 输出"a"-...
tmp++;
}
if(sign)
*tmp++ = '-';
*tmp = '\0';
//生成的数字是逆序的,所以要逆序输出
len = strlen(str);
for(i=0;i<len/2;i++) //首尾交换,共计 len/2 次
{
c = str[i];
str[i] = str[len-i-1];
str[len-i-1] = c;
}
return str;
}
int main(void)
{
int value,base;
char str[100];
while(1)
{
printf("please input a number and base:");
scanf("%d %d",&value,&base);
printf("my_itoa:%s\n",my_itoa(value,str,base));
printf("itoa:%s\n",itoa(value,str,base));
}
}