时间:2022-07-13 08:28:47 | 栏目:C代码 | 点击:次
C语言的算法设计中,经常会需要用到字符串,而由于c语言中字符串并不是一个默认类型,其标准库stdlib设计了很多函数方便我们处理字符串与其他数值类型之间的转换。
首先放上一段展示各函数使用的代码,大家也可以copy到自己的机器上运行观察
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int num=183;
char str[3];
//itoa函数将整型转换为字符串数值类型
itoa(num,str,10);
printf("%s\n",str);
//atoi函数将字符串转化为整形数值类型
int nums=atoi(str);
printf("%d\n",nums);
double dou=12.432;
char c[80];
char cc[80];
//sprintf函数可以实现其他数值类型到string类型的转换
sprintf(c,"%2.2f",dou);
//还可以实现多个数值和字符串之间的任意连接,反正最后转换成字符串
sprintf(cc,"%2.3f%s",dou,"you");
printf("%s\n",c);
printf("%s\n",cc);
//将单精度或者双精度类型转化为字符串的fcvt和gcvt函数
//fcvt并不能显示小数点位置
double fcvtnum=123.456;
char *fcvtstr;
int decdot,sign;
fcvtstr=fcvt(fcvtnum,2,&decdot,&sign);
printf("%s\n",fcvtstr);
//gcvt能够显示小数点,其第二个参数表示有效位数字
char fcvtstrg[20];
gcvt(fcvtnum,6,fcvtstrg);
printf("%s\n",fcvtstrg);
// strtod和atof能将字符串转化为双精度和单精度类型
printf("字符串转化为双精度浮点数%f\n单精度浮点数%f\n",
strtod(fcvtstrg,NULL),atof(fcvtstrg));
return 0;
}
下面对上面代码用到的各函数分类整理与描述
字符串转化为其他类型
其他数值类型转化为字符串