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進制表示的字元串。
下列函數可以将整數轉換為字元串:
----------------------------------------------------------
函數名 作 用
----------------------------------------------------------
itoa() 将整型值轉換為字元串
itoa() 将長整型值轉換為字元串
ultoa() 将無符号長整型值轉換為字元串
一 atoi 把字元串轉換成整型數
例程式:
#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;
}
二 itoa 把一整數轉換為字元串
例程式:
#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]);
轉載于:https://www.cnblogs.com/yexu200241/p/3720886.html