C语言提供了几个标准库函数,可以将任意类型(整型、长整型、浮点型等)的数字转换为字符串。

一、整型转为字符串

以下是用itoa()函数将整数转换为字符串的一个例子:

  1. # include <stdio. h>
  2. # include <stdlib. h>
  3. void main (void);
  4. void main (void)
  5. {
  6. int num = 100;
  7. char str[25];
  8. itoa(num, str, 10);
  9. printf("The number 'num' is %d and the string 'str' is %s. \n" , num, str);
  10. }

itoa()函数有3个参数:第一个参数是要转换的数字,第二个参数是要写入转换结果的目标字符串,第三个参数是转移数字时所用的基数。在上例中,转换基数为10。
下列函数可以将整数转换为字符串:

  1. ----------------------------------------------------------
  2. 函数名
  3. ----------------------------------------------------------
  4. itoa() 将整型值转换为字符串
  5. itoa() 将长整型值转换为字符串
  6. ultoa() 将无符号长整型值转换为字符串
  7. ----------------------------------------------------------

请注意,上述函数与ANSI标准是不兼容的。能将整数转换为字符串而且与ANSI标准兼容的方法是使用sprintf()函数,请看下例:

  1. #include<stdio.h>
  2. #include <stdlib. h>
  3. void main (void);
  4. void main (void)
  5. {
  6. int num = 100;
  7. char str[25];
  8. sprintf(str, " %d" , num);
  9. printf ("The number 'num' is %d and the string 'str' is %s. \n" , num, str);
  10. }

二、浮点数转为字符串

在将浮点型数字转换为字符串时,需要使用另外一组函数。以下是用fcvt()函数将浮点型值转换为字符串的一个例子:

  1. # include <stdio. h>
  2. # include <stdlib. h>
  3. void main (void);
  4. void main (void)
  5. {
  6. double num = 12345.678;
  7. char * sir;
  8. int dec_pl, sign, ndigits = 3; /* Keep 3 digits of precision. * /
  9. str = fcvt(num, ndigits, &dec-pl, &sign); /* Convert the float
  10. to a string. * /
  11. printf("Original number; %f\n" , num) ; /* Print the original
  12. floating-point
  13. value. * /
  14. printf ("Converted string; %s\n",str); /* Print the converted
  15. string's value. * /
  16. printf ("Decimal place: %d\n" , dec-pi) ; /* Print the location of
  17. the decimal point. * /
  18. printf ("Sign: %d\n" , sign) ; /* Print the sign.
  19. 0 = positive,
  20. 1 = negative. * /
  21. }


fcvt()函数和itoa()函数有数大的差别。
fcvt()函数有4个参数:第一个参数是要转换的浮点型值;第二个参数是转换结果中十进制小数点右侧的位数;第三个参数是指向一个整数的指针,该整数用来返回转换结果中十进制小数点的位置;第四个参数也是指向一个整数的指针,该整数用来返回转换结果的符号(0对应于正值,1对应于负值)。

需要注意的是,fcvt()函数的转换结果中并不真正包含十进制小数点,为此,fcvt()函数返回在转换结果中十进制小数点应该占据的位置。在上例中,整型变量dec_pl的结果值为5,因为在转换结果中十进制小数点应该位于第5位后面。如果你要求转换结果中包含十进制小数点,你可以使用gcvt()函数(见下表)。

  1. 下列函数可以将浮点型值转换为字符串:
  2. -------------------------------------------------------------------------
  3. 函数名
  4. -------------------------------------------------------------------------
  5. ecvt() 将双精度浮点型值转换为字符串,转换结果中不包含十进制小数点
  6. fcvt() 以指定位数为转换精度,余同ecvt()
  7. gcvt() 将双精度浮点型值转换为字符串,转换结果中包含十进制小数点
  8. ---------------------------------------------------------------------