字串函式---itoa()函式詳解及實現
阿新 • • 發佈:2019-02-18
itoa()函式
itoa():char *itoa( int value, char *string,int radix);
原型說明:
value:欲轉換的資料。string:目標字串的地址。
radix:轉換後的進位制數,可以是10進位制、16進位制等,範圍必須在 2-36。
功能:將整數value 轉換成字串存入string 指向的記憶體空間 ,radix 為轉換時所用基數(儲存到字串中的資料的進位制基數)。
返回值:函式返回一個指向 str,無錯誤返回。
itoa()函式例項:
itoa()函式實現:#include<iostream> #include<string> using namespace std; int main() { int i=1024; char a[100]={0}; for(int j=2;j<=36;j++) { _itoa_s(i,a,j); cout<<a<<endl; } system("pause"); return 0; }
#include<iostream> #include<string> using namespace std; char *itoa_my(int value,char *string,int radix) { char zm[37]="0123456789abcdefghijklmnopqrstuvwxyz"; char aa[100]={0}; int sum=value; char *cp=string; int i=0; if(radix<2||radix>36)//增加了對錯誤的檢測 { cout<<"error data!"<<endl; return string; } if(value<0) { cout<<"error data!"<<endl; return string; } while(sum>0) { aa[i++]=zm[sum%radix]; sum/=radix; } for(int j=i-1;j>=0;j--) { *cp++=aa[j]; } *cp='\0'; return string; } int main() { int i=1024; char a[100]={0}; for(int j=2;j<=36;j++) { itoa_my(i,a,j); cout<<a<<endl; } system("pause"); return 0; }
執行截圖與原函式輸出一樣,均為: