itoa與atoi ,有的系統庫中有提供這兩個函式的實現,前兩天也自己嘗試寫寫這兩個函式,**實現如下:
/***********==itoa**********===*/
/*把num轉換成字串存放在str 指向的字串裡*/
int myitoa(int num, char *str)
int temp;
int sign = 0; //標記num的符號
char *p;
if (str == null) return -1;
p = str;
/*負數的話取絕對值並改變標記*/
if (num < 0)
num = 0 - num;
sign = 1;
/*把數從低位放進字串*/
dotemp = num % 10; //取num的最後一位
*(p++) = temp + '0';
}while ((num /= 10) != 0);
/*是負數的時候新增『-』*/
if (sign == 1)
*(p++) = '-';
/*給字串的末尾新增 ''/0*/
*(p+1) = '/0';
/*字串逆置*/
while(str < p)
sumi = (int)num;//sumi is the part of int
sumf = num - sumi;//sumf is the part of float
/*int ===> string*/
dowhile((sumi = sumi /10) != 0);
/*******end*******/
if(sign == 1)
pp = str;
pp--;
while(p < pp)
*(str++) = '.';//point
/*float ===> string*/
dowhile(!(sumf > -0.000001 && sumf < 0.000001));
*str = '/0';
return 0;}
/** file : atof.c
*//*string ===> float*/
float atof(const char *str)
/*the part of int*/
while(*str != '.')
/*let p point to the end*/
while(*str != '/0')
str--;//your know!
/*the part of float*/
while(*str != '.')
sumf = 0.1*sumf;
sumf += sumi;
if(sign == 1)
return sumf;}
以上的**簡單測試通過,可能寫得很粗糙,健壯性不是很好,若有什麼地方不足或不對,歡迎指出!
itoa 函式與atoi 函式
目錄 1 itoa 函式 整型轉字元 2 atoi 函式 字元轉整型 以下是用itoa 函式將整數轉換為字串的乙個例子 include include void main void itoa 函式有3個引數 第乙個引數是要轉換的數字,第二個引數是要寫入轉換結果的目標字串,第三個引數是轉移數字時所用 ...
atoi 與 itoa 函式用法
itoa 函式的原型為 char itoa int value,char string,int radix itoa 函式有3個引數 第乙個引數是要轉換的數字,第二個引數是要寫入轉換結果的目標字串,第三個引數是轉換數字時所用的基數。在例中,轉換基數為10。10 十進位制 2 二進位制.itoa並不是...
atoi 與 itoa 函式用法
atoi 函式的原型為 int atoi const char str 函式功能 把字串轉換成整型數 引數str 要進行轉換的字串 返回值 每個函式返回 int 值,此值由將輸入字元作為數字解析而生成。如果該輸入無法轉換為該型別的值,則atoi的返回值為 0 函式說明 引數str字串,如果第乙個非空...