参考原著地址:http://einverne.github.io/post/2015/12/boost-learning-note-1.html
转换对象要求
lexical_cast 对转换对象有如下要求:
- 转换起点对象是可流输出的,即定义了 operator«
- 转换终点对象是可流输入的,即定义了 operator»
- 转换终点对象必须是可缺省构造和可拷贝构造的
C++中内建类型(int,double等)和std::string 都是符合三个条件的。
1 #include <boost/lexical_cast.hpp> 2 using namespace boost; 3 #include <iostream> 4 using namespace std; 5 using boost::lexical_cast; 6 7 int main() 8 { 9 //lexical_cast在转换字符串时,字符串中只能包含数字和小数点,不能出现除e/E以外的英文字符或者其他非数字字符。 10 int a = lexical_cast<int>("123"); 11 long b = lexical_cast<long>("2015"); 12 double c = lexical_cast<double>("123.12"); 13 14 cout<< a << b << c <<endl; 15 16 //数字转换成字符串时不支持高级格式控制 17 string str = lexical_cast<string>(1234); 18 cout<<str<<endl; 19 20 cout<<lexical_cast<string>(1.23)<<endl; 21 cout<<lexical_cast<string>(0x11)<<endl; 22 23 //try catch 24 //当 lexical_cast 无法执行转换时会抛出异常 bad_lexical_cast ,它是 std::bad_cast 的派生类。可以使用 try/catch 块来保护代码 25 try 26 { 27 cout<<lexical_cast<int>("0x100"); 28 cout<<lexical_cast<bool>("false"); 29 } 30 catch(bad_lexical_cast& e) 31 { 32 cout<<"error:"<<e.what()<<endl; 33 } 34 char i = getchar(); 35 return 0; 36 }