C++使用boost::lexical_cast進(jìn)行數(shù)值轉(zhuǎn)換
在STL庫中,我們可以通過stringstream來實(shí)現(xiàn)字符串和數(shù)字間的轉(zhuǎn)換:
int i = 0;
stringstream ss;
ss << "123";
ss >> i;但stringstream是沒有錯(cuò)誤檢查的功能,例如對如如下代碼,會將i給賦值為12.
ss << "12.3";
ss >> i;甚至連這樣的代碼都能正常運(yùn)行:
ss << "hello world";
ss >> i;這顯然不是我們所想要看到的。為了解決這一問題,可以通過boost::lexical_cast來實(shí)現(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機(jī)制數(shù)字的轉(zhuǎn)換,可以以如下方式進(jì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進(jìn)行數(shù)值轉(zhuǎn)換的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- C++強(qiáng)制類型轉(zhuǎn)換(static_cast、dynamic_cast、const_cast、reinterpret_cast)
- c++中的const_cast用法大全
- 解析C++編程中的bad_cast異常
- C++中的類型轉(zhuǎn)換static_cast、dynamic_cast、const_cast和reinterpret_cast總結(jié)
- c++ dynamic_cast與static_cast使用方法示例
- C++中4種類型轉(zhuǎn)換方式 cast操作詳解
- C++ 中dynamic_cast<>的使用方法小結(jié)
- C++四種cast使用詳細(xì)介紹
相關(guān)文章
深入探討POJ 2312 Battle City 優(yōu)先隊(duì)列+BFS
本篇文章是對優(yōu)先隊(duì)列+BFS進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05

