跳轉到內容

C 程式設計/stdlib.h/itoa

來自華夏公益教科書,自由的教科書

itoainteger to ASCII)函式是標準 C 程式語言的廣泛非標準擴充套件。它不能移植地使用,因為它沒有在任何 C 語言標準中定義;但是,編譯器通常透過標頭檔案 <stdlib.h> 在非標準模式下提供它,因為它是在標準庫函式 atoi 的邏輯對應物。

void itoa(int input, char *buffer, int radix)

itoa 接受整數輸入值 input 並將其轉換為以 radix 為基數的數字。結果數字(以 radix 為基數的數字序列)被寫入到輸出緩衝區 buffer 中。

根據實現方式,itoa 可能返回指向 buffer 中第一個字元的指標,或者設計為如果傳遞一個空 buffer 則該函式將返回本來寫入到有效 buffer 中的字串的長度。

要將數字轉換為以 8(八進位制)、10(十進位制)或 16(十六進位制)為基數的字串,可以使用標準庫函式 sprintf 作為標準合規的替代方案。

K&R 實現

[編輯 | 編輯原始碼]

函式 itoa 出現在 Kernighan 和 Ritchie 的《C 程式語言》第一版中,第 60 頁。第二版《C 程式語言》(“K&R2”)包含 itoa 的以下實現,第 64 頁 [對於西班牙語版本,請參閱第 47 頁]。這本書指出該實現存在幾個問題,包括它沒有正確處理最負數 -2字長-1[1]

 /* itoa:  convert n to characters in s */
 void itoa(int n, char s[])
 {
     int i, sign;
 
     if ((sign = n) < 0)  /* record sign */
         n = -n;          /* make n positive */
     i = 0;
     do {       /* generate digits in reverse order */
         s[i++] = n % 10 + '0';   /* get next digit */
     } while ((n /= 10) > 0);     /* delete it */
     if (sign < 0)
         s[i++] = '-';
     s[i] = '\0';
     reverse(s);
 }

上面使用的函式 reverse 在前面兩頁實現。

 #include <string.h>
 
 /* reverse:  reverse string s in place */
 void reverse(char s[])
 {
     int i, j;
     char c;
 
     for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
         c = s[i];
         s[i] = s[j];
         s[j] = c;
     }
 }

其他出現

[編輯 | 編輯原始碼]

itoa 函式(以及類似的函式 ftoa,它將浮點數轉換為字串)在第一版 Unix 手冊中列出。[2] 不同於上面的版本,Unix 庫版本具有大致等效於以下內容的介面:

void itoa(int input, void (*subr)(char))

它將在輸出字串中的每個字元上呼叫回撥例程 subr,從而消除了需要一個足夠大的緩衝區來容納整個字串。


參考資料

[編輯 | 編輯原始碼]
  1. 有關此練習的解決方案,請參閱 clc-wiki.net 上的 "K&R2 solutions"
  2. "Unix Programmer's Manual",1971 年 11 月 3 日。部分 "Library routines"
[編輯 | 編輯原始碼]
華夏公益教科書