c语言字符串类型转换
目录
atoi() – 字符串转整数
声明:
int atoi(const char *str)
如果没有执行有效的转换,则返回0
举个栗子:
// #include<stdio.h>
// #include<stdlib.h>
char str[] = "519";
int a = atoi(str);
a = a + 1;
printf("%d",a);
// 输出:520
查看更多:https://www.runoob.com/cprogramming/c-function-atoi.html
atol() – 字符串转长整数
声明:
long int atol(const char *str)
查看更多:https://www.runoob.com/cprogramming/c-function-atol.html
atof() – 字符串转浮点数
声明:
double atof(const char *str)
查看更多:https://www.runoob.com/cprogramming/c-function-atof.html
strol() – 字符串转长整数
声明:
long int strtol(const char *str, char **endptr, int base)
参数解释:
- str用于转换的字符串
- endptr是一个传出参数,函数返回时指向后面未被识别的第一个字符。
- 参数base代表采用的进制方式
实例:
char str[] = "65 It's a number";
char *ptr;
int num;
num = strtol(str,&ptr,10);
printf("%d\n",num);
puts(ptr);
/*输出:
65
It's a number
*/
查看更多:
https://www.runoob.com/cprogramming/c-function-strtol.html
https://baike.baidu.com/item/strtol/6134558?fr=aladdin
stroul() – 字符串转无符号长整数
声明:
unsigned long int strtoul(const char *str, char **endptr, int base)
与strol()
类似
查看更多:https://www.runoob.com/cprogramming/c-function-strtoul.html
strod() – 字符串转浮点数
声明:
double strtod(const char *str, char **endptr)
实例:
char str[] = "3.14159 It's a number";
char *ptr;
double num;
num = strtod(str,&ptr);
printf("%lf\n",num);
puts(ptr);
/*输出:
3.141590
It's a number
*/
查看更多:https://www.runoob.com/cprogramming/c-function-strtod.html
sprintf() – 格式化输出到字符串
这个函数是另一个标准库<stdio.h>的
声明:
int sprintf(char *str, const char *format, ...)
sprintf()
和printf()
的用法相似,只不过不是格式化输出到屏幕,而是格式化输出到一个字符串变量
实例:
// include<stdio.h>
char str[80];
sprintf(str, "Pi 的值 = %f", 3.14159);
puts(str);
// 输出:Pi 的值 = 3.141590
查看更多:https://www.runoob.com/cprogramming/c-function-sprintf.html
拓展函数(非标准库函数)
-
itoa():将整型值转换为字符串。
-
ltoa():将长整型值转换为字符串。
-
ultoa():将无符号长整型值转换为字符串。
-
gcvt():将浮点型数转换为字符串,取四舍五入。
-
ecvt():将双精度浮点型值转换为字符串,转换结果中不包含十进制小数点。
-
fcvt():指定位数为转换精度,其余同ecvt()。