c语言字符串类型转换

c语言字符串类型转换

c标准库 - <stdlib.h>

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()。

查看更多:https://www.runoob.com/w3cnote/c-int2str.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值