C++使用boost::lexical_cast進行數(shù)值轉(zhuǎn)換
在STL庫中,我們可以通過stringstream來實現(xiàn)字符串和數(shù)字間的轉(zhuǎn)換:
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來實現(xiàn)數(shù)值轉(zhuǎn)換:
int i = boost::lexical_cast<int>("123");
double d = boost::lexical_cast<double>("12.3");對于非法的轉(zhuǎn)換,則會拋異常:
try
{
int i = boost::lexical_cast<int>("12.3");
}
catch (boost::bad_lexical_cast& e)
{
cout << e.what() << endl;
}對于16機制數(shù)字的轉(zhuǎn)換,可以以如下方式進行:
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");
}到此這篇關(guān)于C++使用boost::lexical_cast進行數(shù)值轉(zhuǎn)換的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
深入探討POJ 2312 Battle City 優(yōu)先隊列+BFS
本篇文章是對優(yōu)先隊列+BFS進行了詳細的分析介紹,需要的朋友參考下2013-05-05

