天天看點

atoi 與 itoa 函數的内部實作

                       C語言提供了幾個标準庫函數,可以将任意類型(整型、長整型、浮點型等)的數字轉換為字元串。以下是用itoa()函數将整數轉 換為字元串的一個例子:

       atoi     把字元串轉換成整型數

       itoa     把一整數轉換為字元串

#include "stdio.h"#include "ctype.h"#include "stdlib.h"/*Converts a character string into an int or long将一個字元串轉化為整數*/int my_atoi(char s[]){ int i,n,sign; for(i=;isspace(s[i]);i++);   //跳過空白 sign=(s[i]=='-')?:; if(s[i]=='+'||s[i]==' -')     //跳過符号位  i++; for(n=;isdigit(s[i]);i++)  n=*n+(s[i]-'0');        //将數字字元轉換成整形數字 return sign*n;}/*Converts an int or long into a character string将一個整數轉化為字元串*/void my_itoa(int n,char s[]){ int i,j,sign; if((sign=n)<)    //記錄符号  n=-n;         //使n成為正數 i=; do{  s[i++]=n%+'0';    //取下一個數字 }while((n/=)>);      //循環相除 if(sign<)  s[i++]='-'; s[i]='\0'; for(j=i;j>=;j--)        //生成的數字是逆序的,是以要逆序輸出  printf("%c",s[j]);}void main(){ int n; char str[]; my_itoa(,str); printf("\n"); printf("%d\n",my_atoi("123")); system("pause");}
           

再分享一下我老師大神的人工智能教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智能的隊伍中來!https://blog.csdn.net/jiangjunshow

                       C語言提供了幾個标準庫函數,可以将任意類型(整型、長整型、浮點型等)的數字轉換為字元串。以下是用itoa()函數将整數轉 換為字元串的一個例子:

       atoi     把字元串轉換成整型數

       itoa     把一整數轉換為字元串

#include "stdio.h"#include "ctype.h"#include "stdlib.h"/*Converts a character string into an int or long将一個字元串轉化為整數*/int my_atoi(char s[]){ int i,n,sign; for(i=;isspace(s[i]);i++);   //跳過空白 sign=(s[i]=='-')?:; if(s[i]=='+'||s[i]==' -')     //跳過符号位  i++; for(n=;isdigit(s[i]);i++)  n=*n+(s[i]-'0');        //将數字字元轉換成整形數字 return sign*n;}/*Converts an int or long into a character string将一個整數轉化為字元串*/void my_itoa(int n,char s[]){ int i,j,sign; if((sign=n)<)    //記錄符号  n=-n;         //使n成為正數 i=; do{  s[i++]=n%+'0';    //取下一個數字 }while((n/=)>);      //循環相除 if(sign<)  s[i++]='-'; s[i]='\0'; for(j=i;j>=;j--)        //生成的數字是逆序的,是以要逆序輸出  printf("%c",s[j]);}void main(){ int n; char str[]; my_itoa(,str); printf("\n"); printf("%d\n",my_atoi("123")); system("pause");}