用boost::lexical_cast進行數值轉換


在STL庫中,我們可以通過stringstream來實現字符串和數字間的轉換:

    int i = 0;
    stringstream ss;

    ss << "123";
    ss >> i;

但stringstream是沒有錯誤檢查的功能,例如對如如下代碼,會將i給賦值為12.

    ss << "12.3";
    ss >> i;

甚至連這樣的代碼都能正常運行:

    ss << "hello world";
    ss >> i;

這顯然不是我們所想要看到的。為了解決這一問題,可以通過boost::lexical_cast來實現數值轉換:

    int i = boost::lexical_cast<int>("123");
    double d = boost::lexical_cast<double>("12.3");

對於非法的轉換,則會拋異常:

    try
    {
        int i = boost::lexical_cast<int>("12.3");
    }
    catch (boost::bad_lexical_cast& e)
    {
        cout << e.what() << endl;
    }

對於16機制數字的轉換,可以以如下方式進行:

    template <typename ElemT>
    struct HexTo {
        ElemT value;
        operator ElemT() const {return value;}
        friend std::istream& operator>>(std::istream& in, HexTo& out) {
            in >> std::hex >> out.value;
            return in;
        }
    };

    int main(void)
    {
        int x = boost::lexical_cast<HexTo<int>>("0x10");
    }

 


免責聲明!

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



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