先看下itoa()的函數說明吧:
功 能:把一整數轉換為字串
用 法:char *itoa(int value, char *string, int radix);
詳細解釋:itoa是英文integer to array(將int整型數轉化為一個字串,並將值儲存在數組string中)的縮寫.
參數: value: 待轉化的整數。
radix: 是基數的意思,即先將value轉化為radix進位的數,範圍介於2-36,比如10表示10進位,16表示16進位。
* string: 儲存轉換後得到的字串。
傳回值: char * : 指向產生的字串, 同*string。
備忘:該函數的標頭檔是"stdlib.h" (包含在iostream裡面)
記住一點:itoa並不是一個標準的C函數,它是Windows特有的,如果要寫跨平台的程式,請用sprintf。
是Windows平台下擴充的,標準庫中有sprintf,功能比這個更強,用法跟printf類似。
雖然可能itoa無法使用,但是我們可以編寫自己的itoa()函數,以下是實現原始碼(來源網路):
char*my_itoa(int num,char*str,int radix)<br />{<br /> const char table[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;<br /> char*ptr=str ;<br /> bool negative=false ;<br /> if(num==0)<br /> {<br /> //num=0<br /> *ptr++='0' ;<br /> *ptr='/0' ;<br /> // don`t forget the end of the string is '/0'!!!!!!!!!<br /> return str ;<br /> }<br /> if(num<0)<br /> {<br /> //if num is negative ,the add '-'and change num to positive<br /> *ptr++='-' ;<br /> num*=-1 ;<br /> negative=true ;<br /> }<br /> while(num)<br /> {<br /> *ptr++=table[num%radix];<br /> num/=radix ;<br /> }<br /> *ptr='/0' ;<br /> //if num is negative ,the add '-'and change num to positive<br /> // in the below, we have to converse the string<br /> char*start=(negative?str+1:str);<br /> //now start points the head of the string<br /> ptr--;<br /> //now prt points the end of the string<br /> while(start<ptr)<br /> {<br /> char temp=*start ;<br /> *start=*ptr ;<br /> *ptr=temp ;<br /> start++;<br /> ptr--;<br /> }<br /> return str ;<br />}
程式的測試如下:
#include <iostream><br />using namespace std;<br />int main()<br />{<br />int a=15;<br />char str[100];<br />my_itoa(a,str,15);<br />cout<<str<<endl;<br />return 0;<br />}
對於已經轉換到指定進位的數,此時是字串,我們可以再轉換為整型(2~10進位才可以),比如:
int main()<br />{<br />int a=15;<br />char str[100];<br />int n=atoi(my_itoa(a,str,2));<br />cout<<n<<endl;<br />return 0;<br />}
備忘:atoi()是標準庫裡面的函數,在C/C++語言參考函數裡面有,而itoa()卻沒有,對此我們最好自己實現itoa()函數。