关于Linux环境下字符串和数值型的相互转化问题
一、字符串转换成数值型
C 库函数 - atoi(),atol(),atof()
1、atoi()
atoi()原型: int atoi(const char *str ); C 标准库 - <stdlib.h>
函数功能:把字符串转换成整型数。
参数str:要进行转换的字符串。
返回值:每个函数返回 int 类型的值。如果没有执行有效的转换,则返回0。
2、atol()
atol()原型: long int atol(const char *str); C 标准库 - <stdlib.h>
函数功能:把字符串转换成长整数。
参数str:要进行转换的字符串。
返回值:每个函数返回 long int 类型的值。如果没有执行有效的转换,则返回0。
3、atof()
atof()原型:double atof(const char *str); C 标准库 - <stdlib.h>
函数功能:把字符串转换成double类型的浮点数。
参数str:要进行转换的字符串。
返回值:每个函数返回 double float 类型的值。如果没有执行有效的转换,则返回0.0。
代码案例:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char test[5] = "1234";
printf("test = %s\n", test);
printf("test = %d\n", atoi(test));
printf("test = %ld\n", atol(test));
printf("test = %f\n", atof(test));
return 0;
}
运行结果:
test = 1234
test = 1234
test = 1234
test = 1234.000000
二、数值型转换为字符串
C 库函数 - sprintf()
(因为再Linux环境下, stdlib.h 库中并没有itoa等将数值型转换为字符串的函数,所以我们使用sprintf()函数来代替实现这种功能)
sprintf()原型:int sprintf(char *str, char * format [, argument, …]);
函数功能:将格式化的数据写入字符串。
参数:str为要写入的字符串;format为格式化字符串;argument为变量。
代码案例:
#include <stdio.h>
int main()
{
char test[100] = {0};
sprintf(test, "%d", 1234);
printf("test = %s\n", test);
sprintf(test, "%ld", 12345678999);
printf("test = %s\n", test);
sprintf(test, "%f", 12345.6789);
printf("test = %s\n", test);
return 0;
}
运行结果:
test = 1234
test = 12345678999
test = 12345.678900