C語言提供了幾個標准庫函數,能夠將隨意類型(整型、長整型、浮點型等)的數字轉換為字符串。下面是用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進制表示的字符串。
函數名: atol
功 能: 把字符串轉換成長整型數
用 法: long atol(const char *nptr);
程序例:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
long l;
char *str = "98765432";
l = atol(str); /* 原來為l = atol(lstr); */
printf("string = %s integer = %ld/n", str, l);
return(0);
}
atol(將字符串轉換成長整型數)
相關函數 atof,atoi,strtod,strtol,strtoul
表頭文件 #include<stdlib.h>
定義函數 long atol(const char *nptr);
函數說明 atol()會掃描參數nptr字符串,跳過前面的空格字符,直到遇上數字或正負符號才開始做轉換,而再遇到非數字或字符串結束時('/0')才結束轉換,並將結果返回。
返回值 返回轉換后的長整型數。
附加說明 atol()與使用strtol(nptr,(char**)NULL,10);結果同樣。
范例 /*將字符串a與字符串b轉換成數字后相加*/
#include<stdlib.h>
main()
{
char a[]=”1000000000”;
char b[]=” 234567890”;
long c;
c=atol(a)+atol(b);
printf(“c=%d/n”,c);
}
運行 c=1234567890