【練習題】atoi和itoa函數的實現,練習題atoiitoa
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;elsereturn 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;elseuvalue = (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));}}