C语言中将数字转换为字符串的方法

C语言提供了几个标准库函数,能够将任意类型(整型、长整型、浮点型等)的数字转换为字符串。如下是用itoa()函数将整数转换为字符串的一个例子:


# include <stdio. h>
# include <stdlib. h>
void main (void);
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。


下列函数能够将整数转换为字符串:
----------------------------------------------------------
    函数名                  做  用
----------------------------------------------------------
    itoa()                将整型值转换为字符串
    itoa()                将长整型值转换为字符串
    ultoa()               将无符号长整型值转换为字符串
----------------------------------------------------------
请注意,上述函数与ANSI标准是不兼容的。能将整数转换为字符串并且与ANSI标准兼容的方法是使用sprintf()函数,请看下例:     #include<stdio.h>   # include <stdlib. h> void main (void); void main (void) {     int num = 100;     char str[25];     sprintf(str, " %d" , num);    printf ("The number 'num' is %d and the string 'str' is %s. \n" ,                           num, str); }       在将浮点型数字转换为字符串时,须要使用另一组函数。如下是用fcvt()函数将浮点型值转换为字符串的一个例子:  # include <stdio. h> # include <stdlib. h> void main (void); void main (void) {     double num = 12345.678;     char * sir;     int dec_pl, sign, ndigits = 3; /* Keep 3 digits of precision. * /     str = fcvt(num, ndigits, &dec-pl, &sign); /* Convert the float                                                  to a string. * /     printf("Original number; %f\n" , num) ;  /* Print the original                                                  floating-point                                                     value. * /     printf ("Converted string; %s\n",str);    /* Print the converted                                                 string's value. * /     printf ("Decimal place: %d\n" , dec-pi) ; /* Print the location of                                                  the decimal point. * /     printf ("Sign: %d\n" , sign) ;            /* Print the sign.                                                  0 = positive,                                                  1 = negative. * / }   fcvt()函数和itoa()函数有数大的差异。fcvt()函数有4个参数:第一个参数是要转换的浮点型值;第二个参数是转换结果中十进制小数点右侧的位数;第三个参数是指向一个整数的指针,该整数用来返回转换结果中十进制小数点的位置;第四个参数也是指向一个整数的指针,该整数用来返回转换结果的符号(0对应于正值,1对应于负值)。 须要注意的是,fcvt()函数的转换结果中并不真正包含十进制小数点,为此,fcvt()函数返回在转换结果中十进制小数点应该占据的位置。在上例中,整型变量dec_pl的结果值为5,由于在转换结果中十进制小数点应该位于第5位后面。若是你要求转换结果中包含十进制小数点,你能够使用gcvt()函数(见下表)。 下列函数能够将浮点型值转换为字符串: -------------------------------------------------------------------------     函数名             做  用 -------------------------------------------------------------------------     ecvt()    将双精度浮点型值转换为字符串,转换结果中不包含十进制小数点     fcvt()    以指定位数为转换精度,余同ecvt()     gcvt()    将双精度浮点型值转换为字符串,转换结果中包含十进制小数点 -------------------------------------------------------------------------