晕,编译错了
#include <boost/lexical_cast.hpp> #include <string> #include <iostream> /* @brief 实现数字和字符串之间的字面转换 如把123(int)转换成"123"(string) @remark 注意:要转换为数字的字符串不能包含数字、小数点和e/E以外的字符 如:0x100,123L等C++允许的字面数字都不被支持 */ using namespace boost; using namespace std; int main() { //-------------------- // 字符串字面转成数字 //-------------------- int x = lexical_cast<int>("100"); // 字符串100转换成整形100 long y = lexical_cast<long>("1000"); // ... float pai = lexical_cast<float>("3.14159e5"); // 换为数字的字符串不能包含数字、小数点和e/E以外的字符 double e = lexical_cast<double>("2.71828"); cout<< "x value: "<<x<<endl; cout<< "y value: "<<y<<endl; cout<< "pai value: "<<pai<<endl; cout<< "e value: "<<e<<endl; //--------------------- // 数字字面转成字符串 //--------------------- string str1 = lexical_cast<string>(123); string str2 = lexical_cast<string>(0.618); string str3 = lexical_cast<string>(0x10); cout<< "str1: "<<str1<<endl; cout<< "str2: "<<str2<<endl; cout<< "str3: "<<str3<<endl; //--------------------- // 异常外理 //--------------------- try { cout << lexical_cast<int>("0x10")<<endl; // 非法字符,抛出bad_lexical_cast异常 cout << lexical_cast<float>("Hello world!")<<endl; // 非法字符,抛出bad_lexical_cast异常 } catch(const bad_lexical_cast& e) // bad_lexical_cast异常是std::bad_cast的派生类 { cout<< e.what()<<endl; } getchar(); return 0; }
posted on 2011-01-25 22:46 几百人有爱 阅读(500) 评论(0) 编辑 收藏 举报