最近学数据结构老是做实验
常用到字符串和数字的转换
想找却发现网上的资料太散
所以搜集整理一下 方便以后再用
atof(将字符串转换成浮点型数)
atoi(将字符串转换成整型数)
atol(将字符串转换成长整型数)
strtod(将字符串转换成浮点数)
strtol(将字符串转换成长整型数)
strtoul(将字符串转换成无符号长整型数)
toascii(将整型数转换成合法的ASCII 码字符)
toupper(将小写字母转换成大写字母)
tolower(将大写字母转换成小写字母)
atof(将字符串转换成浮点型数)
相关函数 atoi,atol,strtod,strtol,strtoul
表头文件 #include
#include<stdlib.h>
main()
{
char *a=”-100.23”;
char *b=”200e-2”;
float c;
c=atof(a)+atof(b);
printf(“c=%.2f/n”,c);
}
执行 c=-98.23
atoi(将字符串转换成整型数)
相关函数 atof,atol,atrtod,strtol,strtoul
表头文件 #include
#include<stdlib.h>
mian()
{
char a[]=”-100”;
char b[]=”456”;
int c;
c=atoi(a)+atoi(b);
printf(c=%d/n”,c);
}
执行 c=356
atol(将字符串转换成长整型数)
相关函数 atof,atoi,strtod,strtol,strtoul
表头文件 #include
#include<stdlib.h>
main()
{
char a[]=”1000000000”;
char b[]=” 234567890”;
long c;
c=atol(a)+atol(b);
printf(“c=%d/n”,c);
}
执行 c=1234567890
gcvt(将浮点型数转换为字符串,取四舍五入)
相关函数 ecvt,fcvt,sprintf
表头文件 #include
#include<stdlib.h>
main()
{
double a=123.45;
double b=-1234.56;
char *ptr;
int decpt,sign;
gcvt(a,5,ptr);
printf(“a value=%s/n”,ptr);
ptr=gcvt(b,6,ptr);
printf(“b value=%s/n”,ptr);
}
执行 a value=123.45
b value=-1234.56
strtod(将字符串转换成浮点数)
相关函数 atoi,atol,strtod,strtol,strtoul
表头文件 #include
#include<stdlib.h>
mian()
{
char a[]=”1000000000”;
char b[]=”1000000000”;
char c[]=”ffff”;
printf(“a=%d/n”,strtod(a,NULL,10));
printf(“b=%d/n”,strtod(b,NULL,2));
printf(“c=%d/n”,strtod(c,NULL,16));
}
执行 a=1000000000
b=512
c=65535
strtol(将字符串转换成长整型数)
相关函数 atof,atoi,atol,strtod,strtoul
表头文件 #include
#include<stdlib.h>
main()
{
char a[]=”1000000000”;
char b[]=”1000000000”;
char c[]=”ffff”;
printf(“a=%d/n”,strtol(a,NULL,10));
printf(“b=%d/n”,strtol(b,NULL,2));
printf(“c=%d/n”,strtol(c,NULL,16));
}
执行 a=1000000000
b=512
c=65535
strtoul(将字符串转换成无符号长整型数)
相关函数 atof,atoi,atol,strtod,strtol
表头文件 #include
#include<stdlib.h>
main()
{
int a=217;
char b;
printf(“before toascii () : a value =%d(%c)/n”,a,a);
b=toascii(a);
printf(“after toascii() : a value =%d(%c)/n”,b,b);
}
执行 before toascii() : a value =217()
after toascii() : a value =89(Y)
tolower(将大写字母转换成小写字母)
相关函数 isalpha,toupper
表头文件 #include
#include<ctype.h>
main()
{
char s[]=”aBcDeFgH12345;!#$”;
int i;
printf(“before tolower() : %s/n”,s);
for(i=0;I<sizeof(s);i++)
s[i]=tolower(s[i]);
printf(“after tolower() : %s/n”,s);
}
执行 before tolower() : aBcDeFgH12345;!#after tolower() : abcdefgh12345;!#
toupper(将小写字母转换成大写字母)
相关函数 isalpha,tolower
表头文件 #include
#include<ctype.h>
main()
{
char s[]=”aBcDeFgH12345;!#$”;
int i;
printf(“before toupper() : %s/n”,s);
for(i=0;I<sizeof(s);i++)
s[i]=toupper(s[i]);
printf(“after toupper() : %s/n”,s);
}
执行 before toupper() : aBcDeFgH12345;!#after toupper() : ABCDEFGH12345;!#