Boost::lexical_cast類型轉換


1、字符串->數值

C++代碼

 1 #include <boost/lexical_cast.hpp> 
 2 #include <iostream> 
 3 int main() 
 4 { 
 5     using boost::lexical_cast; 
 6     int a = lexical_cast<int>("123"); 
 7     double b = lexical_cast<double>("123.12"); 
 8     std::cout<<a<<std::endl 
 9     std::cout<<b<<std::endl; 
10     return 0; 
11 }

2、數值->字符串

C++代碼

 1 #include <boost/lexical_cast.hpp> 
 2 #include <string> 
 3 #include <iostream> 
 4 int main() 
 5 { 
 6     using std::string; 
 7     const double d = 123.12; 
 8     string s = boost::lexical_cast<string>(d); 
 9     std::cout<<s<<std::endl; 
10     return 0; 
11 }

3、異常

  如果轉換發生了意外,lexical_cast會拋出一個bad_lexical_cast異常,因此程序中需要對其進行捕捉。

C++代碼

 1 #include <boost/lexical_cast.hpp> 
 2 #include <iostream> 
 3 int main() 
 4 { 
 5     using std::cout; 
 6     using std::endl; 
 7     int i; 
 8     try 
 9     { 
10         i = boost::lexical_cast<int>("xyz"); 
11     } 
12     catch(boost::bad_lexical_cast& e) 
13     { 
14         cout<<e.what()<<endl; 
15         return 1; 
16     } 
17     cout<<i<<endl; 
18     return 0; 
19 } 

  顯然“xyz”並不能轉換為一個int類型的數值,於是拋出異常,捕捉后輸出“bad lexical cast: source type value could not be interpreted as target”這樣的信息。

4、注意事項

  lexical_cast依賴於字符流std::stringstream,其原理相當簡單:把源類型讀入到字符流中,再寫到目標類型中,就大功告成。


免責聲明!

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



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