C++字符串和数字之间的转换的转换

 

今天牛客网上的剑指offer:https://www.nowcoder.com/practice/bd7f978302044eee894445e244c7eee6?tpId=13&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

我的思路中用到了数字转字符串,于是复习了下数字与字符串相互转换的函数(3)和(5)常用

(1)用sprintf_s函数将数字转换成字符串    

    int i_temp = 2020;
    std::string s_temp;
    char c_temp[20];
    sprintf_s(c_temp, "%d", i_temp);
    s_temp = c_temp;
    std::cout << s_temp << std::endl;

(2)用sscanf函数将字符串转换成数字

    double i_temp;
    char c_temp[20] = "15.234";
    sscanf_s(c_temp, "%lf", &i_temp);
    std::cout << i_temp << std::endl;

(3)atoi, atof, atol, atoll(C++11标准) 函数将字符串转换成int,double, long, long long 型 

    std::string s_temp;
    char c_temp[20] = "1234";
    int i_temp = atoi(c_temp);
    s_temp = c_temp;

    std::string s_temp;
    char c_temp[20] = "1234.1234";
    double i_temp = atof(c_temp);
    s_temp = c_temp;

(4)strtol, strtodstrtofstrtoll,strtold 函数将字符串转换成int,double,float, long long,long double 型

    std::string s_temp;
    char c_temp[20] = "4.1234";
    double a = strtod(c_temp, nullptr);  //后面的参数是如果遇到字符串则是指向字符串的引用

(5)用to_string把数字转化成字符串(我用的就是这种方法)

    double d_temp = 1.567;
    std::string s_temp = to_string(d_temp);

参考:https://www.cnblogs.com/yibeimingyue/p/9996923.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值