天天看點

C語言數字與字元串轉換 atoi()函數、itoa()函數、sprintf()函數

在程式設計中經常需要用到數字與字元串的轉換,下面就總結一下。

1.atoi()

  C/C++标準庫函數,用于字元串到整數的轉換。

  函數原型:int atoi (const char * str);

1 #include <stdio.h>
2 #include <stdlib.h>
3 int main ()
4 {
5     char *numchars="1234";
6     int num=atoi(numchars);
7     printf("%d\n",num);
8     return 0;
9 }      

  另外C/C++還提供的标準庫函數有:

  (1)long int atol ( const char * str );  

  (2)double atof (const char* str);

2.itoa()

  不是C/C++标準庫函數,用于整數到字元串的轉換。

  函數原型:

char

*itoa(

int

value,

char

*string,

int

radix);

1 #include <stdio.h>
 2 #include <stdlib.h>
 3 int main ()
 4 {
 5     int num=1234;
 6     int radix=8;
 7     char res[20];
 8     itoa(num,res,radix);
 9     printf("%d(10)=%s(%d)\n",num,res,radix);    //輸出:1234(10)=2322(8)
10     return 0;
11 }      

3.sprintf()

  C/C++标準庫函數,可以用于整數到字元串的轉換。

  sprintf:Write formatted data to string。

  sprintf作用是将printf的輸出結果儲存在字元串數組中。

1 #include <stdio.h>
 2 #include <stdlib.h>
 3 int main ()
 4 {
 5     int num=1234;
 6     char res[20];
 7     sprintf(res,"%0o",num);
 8     printf("%s\n",res); //8進制輸出:2322
 9 
10     sprintf(res,"%0x",num);
11     printf("%s\n",res); //16進制輸出:4d2
12     return 0;
13 }