天天看點

C語言itoa()函數和atoi()函數

以下是用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進制表示的字元串。

以下為atoi用法

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
   int val;
   char str[20];
   
   strcpy(str, "98993489");
   val = atoi(str);
   printf("字元串值 = %s, 整型值 = %d\n", str, val);

   strcpy(str, "runoob.com");
   val = atoi(str);
   printf("字元串值 = %s, 整型值 = %d\n", str, val);

   return(0);
}      

轉載于:https://www.cnblogs.com/nanqiang/p/9959084.html