C語言itoa()函數和atoi()函數詳解(整數轉字符C實現)


C語言提供了幾個標准庫函數,可以將任意類型(整型、長整型、浮點型等)的數字轉換為字符串。


1.int/float to string/array:

C語言提供了幾個標准庫函數,可以將任意類型(整型、長整型、浮點型等)的數字轉換為字符串,下面列舉了各函數的方法及其說明。
● itoa():將整型值轉換為字符串。
● ltoa():將長整型值轉換為字符串。
● ultoa():將無符號長整型值轉換為字符串。
● gcvt():將浮點型數轉換為字符串,取四舍五入。
● ecvt():將雙精度浮點型值轉換為字符串,轉換結果中不包含十進制小數點。
● fcvt():指定位數為轉換精度,其余同ecvt()。

除此外,還可以使用 sprintf系列函數把數字轉換成字符串,其比itoa()系列函數運行速度慢

2. string/array to int/float
C/C++語言提供了幾個標准庫函數,可以將字符串轉換為任意類型(整型、長整型、浮點型等)。
● atof():將字符串轉換為雙精度浮點型值。
● atoi():將字符串轉換為整型值。
● atol():將字符串轉換為長整型值。
● strtod():將字符串轉換為雙精度浮點型值,並報告不能被轉換的所有剩余數字。
● strtol():將字符串轉換為長整值,並報告不能被轉換的所有剩余數字。
● strtoul():將字符串轉換為無符號長整型值,並報告不能被轉換的所有剩余數字。

以下是用itoa()函數將整數轉換為字符串的一個例子:
# include <stdio.h>
# include <stdlib.h>
void main (void)
{
int num = 100;
char str[25];
itoa(num, str, 10);
printf("The number 'num' is %d and the string 'str' is %s. \n" ,
num, str);
}

itoa()函數有3個參數:第一個參數是要轉換的數字,第二個參數是要寫入轉換結果的目標字符串,第三個參數是轉移數字時所用 的基數。在上例中,轉換基數為10。10:十進制;2:二進制...

itoa並不是一個標准的C函數,它是Windows特有的,如果要寫跨平台的程序,請用sprintf。是Windows平台下擴展的,標准庫中有sprintf,功能比這個更強,用法跟printf類似:

char str[255];
sprintf(str, "%x", 100); //將100轉為16進制表示的字符串。

下列函數可以將整數轉換為字符串:
----------------------------------------------------------
函數名 用
----------------------------------------------------------
itoa() 將整型值轉換為字符串
itoa() 將長整型值轉換為字符串
ultoa() 將無符號長整型值轉換為字符串

一、atoi()——把字符串轉換成整型數
考點:字符串轉換為數字時,對相關ASCII碼的理解。
 
C實現:
#include <ctype.h>
#include <stdio.h>
int atoi (char s[]);
int main(void )
{
char s[100];
gets(s);
printf("integer=%d\n",atoi(s));
return 0;
}
int atoi (char s[])
{
int i,n,sign;
for(i=0;isspace(s[i]);i++)//跳過空白符;
sign=(s[i]=='-')?-1:1;
if(s[i]=='+'||s[i]==' -')//跳過符號
  i++;
for(n=0;isdigit(s[i]);i++)
        n=10*n+(s[i]-'0');//將數字字符轉換成整形數字
return sign *n;
}


C++實現:
1    #include <iostream>
2    using namespace std;
3  
4    int str2int(const char *str)
5    {
6        int temp = 0;
7        const char *ptr = str;  //ptr保存str字符串開頭
8  
9        if (*str == '-' || *str == '+')  //如果第一個字符是正負號,
10       {                      //則移到下一個字符
11           str++;
12       }
13       while(*str != 0)
14       {
15           if ((*str < '0') || (*str > '9'))  //如果當前字符不是數字
16           {                       //則退出循環
17               break;
18           }
19           temp = temp * 10 + (*str - '0'); //如果當前字符是數字則計算數值
20           str++;      //移到下一個字符
21       }  
22       if (*ptr == '-')     //如果字符串是以“-”開頭,則轉換成其相反數
23       {
24           temp = -temp;
25       }
26 
27       return temp;
28   }
29 
30   int main()
31   {
32       int n = 0;  
33       char p[10] = "";
34 
35       cin.getline(p, 20);   //從終端獲取一個字符串
36       n = str2int(p);      //把字符串轉換成整型數
37      
38       cout << n << endl;
39 
40       return 0;
41   }

二、itoa()——把一整數轉換為字符串
通過把整數的各位上的數字加“0”轉換成char類型並存到字符數組中。但是要注意,需要采用字符串逆序的方法
 
C語言實現:
#include <ctype.h>
#include <stdio.h>
void      itoa (int n,char s[]);
//atoi 函數:將s轉換為整形數
int main(void )
{
int n;
char s[100];
printf("Input n:\n");
scanf("%d",&n);
printf("the string : \n");
itoa (n,s);
return 0;
}
void itoa (int n,char s[])
{
int i,j,sign;
if((sign=n)<0)//記錄符號
n=-n;//使n成為正數
i=0;
do{
        s[i++]=n%10+'0';//取下一個數字
}
while ((n/=10)>0);//刪除該數字
if(sign<0)
s[i++]='-';
s[i]='\0';
for(j=i;j>=0;j--)//生成的數字是逆序的,所以要逆序輸出
       printf("%c",s[j]);
}

是int 轉string類型的一個函數
 
C++實現:
1    #include <iostream>
2    using namespace std;
3   
4    void int2str(int n, char *str)
5    {
6        char buf[10] = "";
7        int i = 0;
8        int len = 0;
9        int temp = n < 0 ? -n: n;  // temp為n的絕對值
10  
11       if (str == NULL)
12       {
13           return;
14       }
15       while(temp)
16       {
17           buf[i++] = (temp % 10) + '0';  //把temp的每一位上的數存入buf
18           temp = temp / 10;
19       }
20  
21       len = n < 0 ? ++i: i;  //如果n是負數,則多需要一位來存儲負號
22       str[i] = 0;            //末尾是結束符0
23       while(1)
24       {
25           i--;
26           if (buf[len-i-1] ==0)
27           {
28               break;
29           }
30           str[i] = buf[len-i-1];  //把buf數組里的字符拷到字符串
31       }
32       if (i == 0 )
33       {
34           str[i] = '-';          //如果是負數,添加一個負號
35       }
36   }
37  
38   int main()
39   {
40       int nNum;
41       char p[10];
42  
43       cout << "Please input an integer:";
44       cin >> nNum;
45       cout << "output: " ;
46       int2str(nNum, p);        //整型轉換成字符串
47       cout<< p << endl;
48  
49       return 0;
50   }
 
參考閱讀:http://blog.sina.com.cn/s/blog_4c8a2a870100qgq7.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM