zoukankan      html  css  js  c++  java
  • C++11的新类型转换方法

    转载自 http://blog.csdn.net/luoweifu/article/details/20493177

    基于C++11标准

    如果你用的编译器是基于最新的C++11标准,那么这个问题就变的很简单,因为<string>中已经封装好了对应的转换方法:

    标准库中定义了to_string(val);可以将其它类型转换为string。还定义了一组stoi(s,p,b)、stol(s,p,b)、stod(s,p,b)等转换函数,可以函数,可以分别转化成int、long、double等.

       stoi(s,p,b);stol(s,p,b);stoul(s,p,b);stoll(s,p,b);stoull(s,p,b);返回s的起始子串(表示整数内容的字符串)的数值,返回值的类型分别为:int、long、unsigned long、long long、unsigned long long.其中b表示转换所用的基数,默认为10(表示十进制).p是size_t的指针,用来保存s中第一个非数值字符的下标,p默认为0,即函数不返回下标.

       stof(s, p); stod(s, p); stold(s, p); 返回s的起始子串(表示浮点数内容)的数值,返回值的类型分别是float、double、long double.参数p的作用与整数转换函数中的一样。

    VS2013下编译通过

    void testTypeConvert()
    {
        //int --> string
        int i = 5;
        string s = to_string(i);
        cout << s << endl;
        //double --> string
        double d = 3.14;
        cout << to_string(d) << endl;
        //long --> string
        long l = 123234567;
        cout << to_string(l) << endl;
        //char --> string
        char c = 'a';
        cout << to_string(c) << endl;    //自动转换成int类型的参数
        //char --> string
        string cStr; cStr += c;
        cout << cStr << endl;
    
    
        s = "123.257";
        //string --> int;
        cout << stoi(s) << endl;
        //string --> int
        cout << stol(s) << endl;
        //string --> float
        cout << stof(s) << endl;
        //string --> doubel
        cout << stod(s) << endl;
    }

    结果如下:

    5

    3.140000

    123234567

    97

    a

     

    123

    123

    123.257

    123.257

  • 相关阅读:
    EncryptionAndDecryptionC# 加密 解密
    EncryptFac 加解密小工具
    Aes加密/解密示例项目
    DES加密解密工具
    DESC加密解密算法
    加解密合集
    Zabbix系列之一——zabbix3.4部署
    Linux下ntpdate时间同步
    SVN服务器搭建实录
    Failed to get D-Bus connection: Operation not permitted解决
  • 原文地址:https://www.cnblogs.com/scarecrow-blog/p/5601466.html
Copyright © 2011-2022 走看看