【練習題】atoi和itoa函數的實現,練習題atoiitoa

來源:互聯網
上載者:User

【練習題】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));}}




相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.