首页 / 操作系统 / Linux / C语言中将数字转换为字符串的方法
C语言提供了几个标准库函数,可以将字符串转换为任意类型(整型、长整型、浮点型等)的数字。以下是用atoi()函数将字符串转换为整数的一个例子: # include <stdio. h> # include <stdlib. h> void main (void) ; void main (void) { int num; char * str = "100"; num = atoi(str); printf("The string "str" is %s and the number "num" is %d.
", str, num); } atoi()函数只有一个参数,即要转换为数字的字符串。atoi()函数的返回值就是转换所得的整型值。 下列函数可以将字符串转换为数字: ------------------------------------------------------------------------ 函数名 作 用 ------------------------------------------------------------------------ atof() 将字符串转换为双精度浮点型值 atoi() 将字符串转换为整型值 atol() 将字符串转换为长整型值 strtod() 将字符串转换为双精度浮点型值,并报告不能被转换的所有剩余数字 strtol() 将字符串转换为长整值,并报告不能被转换的所有剩余数字 strtoul() 将字符串转换为无符号长整型值,并报告不能被转换的所有剩余数字 ------------------------------------------------------------------------ 将字符串转换为数字时可能会导致溢出,如果你使用的是strtoul()这样的函数,你就能检查这种溢出错误。请看下例: # include <stdio. h> # include <stdlib. h> # include <limits. h> void main(void); void main (void) { char* str = "1234567891011121314151617181920" ; unsigned long num; char * leftover; num = strtoul(str, &leftover, 10); printf("Original string: %s
",str); printf("Converted number: %1u
" , num); printf("Leftover characters: %s
" , leftover); } 在上例中,要转换的字符串太长,超出了无符号长整型值的取值范围,因此,strtoul()函数将返回ULONG_MAX(4294967295),并使。char leftover指向字符串中导致溢出的那部分字符;同时,strtoul()函数还将全局变量errno赋值为ERANGE,以通知函数的调用者发生了溢出错误。函数strtod()和strtol()处理溢出错误的方式和函数strtoul()完全相同,你可以从编译程序文档中进一步了解这三个函数的有关细节。C++ 隐式类类型转化 Implicit Class-Type Conversions http://www.linuxidc.com/Linux/2013-01/78071.htmC语言变长数组之剖析 http://www.linuxidc.com/Linux/2013-07/86997.htmC语言需要注意的问题 http://www.linuxidc.com/Linux/2013-05/84301.htmC语言位域的使用及其注意点 http://www.linuxidc.com/Linux/2013-07/87027.htmC语言中简单的for循环和浮点型变量 http://www.linuxidc.com/Linux/2013-08/88514.htm本文永久更新链接地址 :http://www.linuxidc.com/Linux/2015-01/111354.htm
收藏该网址