c语言中字符数组和数字的相互转换函数 | 您所在的位置:网站首页 › 字符1转换为数字1的函数是 › c语言中字符数组和数字的相互转换函数 |
一、c 语言中字符数组和数字的相互转换函数; 相关函数:atof atoi,atol, strtod,strtol,strtoul 在头文件stdlib中 #include (1)atof (将字串转换成浮点型数) ascii to floating 的缩写 char *str = "123.456E2"; double f=atof(str); printf("string = %s double = %lf\n", str, f); //输出结果为:string = 123.456e2 double = 12345.600000 (2) atoi (将字串转换成型数) ascii to integer char *str = "123456789"; int f=atoi(str); printf("string = %s integer = %d\n", str, f); //输出结果为:string = 123456789 integer = 123456789 (3) atol (将字串转换成长型数) ascii to long int和上面的一组功能一样,头文件也相同,只是增添了一个遇到不合条件而终止的指针; 就是一遇到不符合条件的字符,就停止转换,将失败位置的地址放到 endptr 的地址里 (1)strtod(将字符串转成double) string to double char *endptr; char a[] = "1234.567qwert"; printf( "a=%lf ", strtod(a,&endptr)); printf( "%s\n", endptr ); //输出结果为:a=1234.567000 qwert(2)long int strtol(char *nptr,char **endptr,int base); (将字串转换成32位型数)string to long int 其中base是string中数字串的进制 char *endptr; char a[] = "123456.123qwert"; long b=strtol(a,&endptr,10); printf( "a=%ld\n",b ); printf( "fail=%s\n", endptr ); //输出结果为:a=1234567 // fail=.123qwert (3) strtoul (将字串转换成无符号32位型数) string to unsigned long-------------------------------------------------分割线-------------------------------------------------- 既然可以将字符串转成对应的数字,那么反之也可行。下面介绍一下数字如何转成字符串数组 (1)_itoa 函数 英文: integer to array 功能: 将Integer类型转换为base进制,存入字符串数组中 用法:char * _itoa(int value, char *str, int base); 意思,即先将value转化为base进制的数,之后再保存在str中 int num = 123456; char str[25]; _itoa(num, str, 10); printf("integer = %d str = %s\n", num, str); //输出结果为:integer = 123456 str = 123456 (2) _itow 函数 Integer to Wide Char int num=123456; wchar_t str[25]; _itow(num, str, 10); printf("%d\n",sizeof(str[0])); wchar_t 宽字符每个字符占两个字节
|
CopyRight 2018-2019 实验室设备网 版权所有 |