C/C++中int/long/float/double数值类型与字符串互相转换[总结]





memcpy方法可以实现将int等保存到字符类型的数组中。

示例:

long    long_data=-9828;

     unsigned char data[4];

memcpy(data,&t,4); //将long类型的数据用4个char保存。


long my_long_data=0;


memcpy(&tt,data,4);//从4个char中还原出long类型数据。






一、int/long/float/double转字符串

方法1:itoa, ltoa(a表示array数组的意思)

头文件:stdlib.h

示例:

    int a = 3;

    long b = 23;

    char buf1[30] = "";
    itoa(a, buf1, 10);//10表示十进制,buf1保存的内容为"3"
    char buf2[30] = "";
    ltoa(b, buf2, 10);//10表示十进制,buf2保存的内容为"32"

方法2:sprintf

头文件:stdio.h

示例:

    int a = 3;
    float b = 4.2f;
    char buf[30] = "";
    sprintf(buf, "%d,%f", a, b);//buf保存的内容为"3,4.2",可对比printf

方法3:ostringstream

头文件:#include <sstream>

using namespace std;

示例:

    int a = 3;
    float b = 4.2f;
    ostringstream s1;
    s1<    string s2 = s1.str();//s2保存的内容为"3,4.2"

二、字符串转int/long/float/double

方法1:atoi,atol,atof

头文件:stdlib.h

示例:

int a = atoi("32");

long b = atol("333");

double c = atof("23.4");

方法2:strtol, strtod

头文件:stdlib.h

示例:

long b = strtol("333", NULL, 10);//10表示十进制

double c = strtod("32.3", NULL);

方法3:sscanf

头文件:stdio.h

示例:

    int a;
    float b;
    sscanf("23 23.4", "%d %f", &a, &b);//对比scanf

方法4:istringstream

头文件:#include <sstream>

using namespace std;

示例:

    int a;
    float b;
    istringstream s1("23 23.4");
    s1>>a>>b;//对比cin

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/14766028/viewspace-703264/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/14766028/viewspace-703264/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值