1. 程式人生 > >Boost--lexical_cast 一個方便安全高效的string轉換庫

Boost--lexical_cast 一個方便安全高效的string轉換庫

#include "boost\lexical_cast.hpp"
#include <vector>
#include <iostream>
#include <array>

using namespace std;
using boost::lexical_cast;
using boost::bad_lexical_cast;

int main()
{

// C++自帶的函式不好記,且命名不統一,有些a開頭有些是str開頭
/*  string轉成其他型別
atof     Convert string to double (function )
atoi     Convert string to integer (function )
atol     Convert string to long integer (function )
atoll    Convert string to long long integer (function )
strtod   Convert string to double (function )
strtof   Convert string to float (function )
strtol   Convert string to long integer (function )
strtold  Convert string to long double (function )
strtoll  Convert string to long long integer (function )
strtoul  Convert string to unsigned long integer (function )
strtoull Convert string to unsigned long long integer (function )
sscanf()
   
   其他型別轉string需要完全不同的方法
stringstream strm;
strm << int_val;
string s = strm.str();
sprintf()
itoa  // non-standard
*/


    try
    {
        int s = 345;
// 只需要使用同一個函式就可以完成不同型別的轉換
        string str = lexical_cast<string>(s);
        str = "Message: " + lexical_cast<string>('A') + "==" + lexical_cast<string>(34.5);
        cout << str << endl;
//也可以轉成char型別的array
        array<char, 64> msg = lexical_cast< array<char, 64> >(23456);

        s = lexical_cast<int>("5678");
        //s = lexical_cast<int>("56.78"); // bad_lexical_cast
        //s = lexical_cast<int>("3456yut");  // bad_lexical_cast 
        s = lexical_cast<int>("3456yut", 4);  //ok
        cout << s << endl;
    }
    catch(bad_lexical_cast & e)
    {
        cout << "Exception caught:" << e.what() << endl; 
    }
    
}