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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM