c语言中字符数组和数字的相互转换函数

一、c 语言中字符数组数字的相互转换函数;

       相关函数:atof  atoi,atol,

                         strtod,strtol,strtoul

  在头文件stdlib中         #include<stdlib.h>

 (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    宽字符每个字符占两个字节








  • 17
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值