2025年4月11日 星期五 乙巳(蛇)年 正月十二 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

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

时间:12-30来源:作者:点击数:76

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。

下列函数可以将整数转换为字符串:
----------------------------------------------------------
    函数名                  作  用
----------------------------------------------------------
    itoa()                将整型值转换为字符串
    itoa()                将长整型值转换为字符串
    ultoa()               将无符号长整型值转换为字符串
----------------------------------------------------------

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

  • #include<stdio.h>
  • # include <stdlib.h>
  • 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)
  • {
  • 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()    将双精度浮点型值转换为字符串,转换结果中包含十进制小数点
-------------------------------------------------------------------------

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门