boost库学习之 lexical_cast
来源:互联网 发布:java知识分享网 编辑:程序博客网 时间:2024/05/16 23:35
在C中字符串转换为数值,可以使用atoi()、atof()、atol()等,数值转换为字符串可以使用itoa()、sprintf()等,但itoa与编译器有关,并不是标准函数,而sprintf可能会不安全。使用lexical_cast可以很容易地在数值与字符串之间转换,只需在模板参数中指定转换的目标类型即可。如int x = lexical_cast<int>("100");long y = lexical_cast<long>("10000");cout << x << " " << typeid(x).name() << endl;cout << y << " " << typeid(y).name() << endl;string strX = lexical_cast<string>(x);cout << strX << endl;lexical_cast除了转换数值和字符串也可以只使用1或0转换bool类型.当lexical_cast无法执行转换操作时会抛出bad_lexical_cast异常,它继承std::bad_cast,所以我们应使用try/catch保护转换代码,如try{int x = lexical_cast<int>("100");int y = lexical_cast<int>("test");} catch (bad_lexical_cast& ex) {cout << ex.what() << endl;}代码输出:bad lexical cast: source type value not be interpreted as target如果被转换的参数是NULL, 如 int x = lexical_cast<int>(NULL); 那么x 为0我们也可根据该异常来编写验证数字字符串的合法性template<typename T>bool isValidNumStr(const char* str) {if (str == nullptr) {return false;}try {lexical_cast<T>(str);return true;}catch (bad_lexical_cast& ex) {return false;}}
0 0
- boost库学习之 lexical_cast
- 学习boost之lexical_cast
- boost学习之-lexical_cast
- boost学习之lexical_cast
- C++学习 boost学习之-lexical_cast
- boost程序库学习-lexical_cast
- BOOST库 之 lexical_cast类型转换
- boost之lexical_cast
- Boost 之 lexical_cast
- boost之lexical_cast使用
- boost之lexical_cast
- C++ boost之 conversion/lexical_cast
- boost之lexical_cast简易说明
- boost之lexical_cast库,数值/字符串转换及其异常处理
- boost库之字符串与文本处理——lexical_cast
- boost::lexical_cast库的使用
- Boost::lexical_cast
- Boost :Lexical_cast
- 前端进阶学习(四) --css框架再探
- 大三上------期末总结
- AndroidXML文件属性的详解
- PHP 连接 SQL2008
- Rotate Image
- boost库学习之 lexical_cast
- POJ 2337 Catenyms(有向图欧拉路径判定&&打印)
- OpenCV学习之CvMat的用法详解及实例(一)
- Java EE
- 2015-1-30-工作日志-刘婉
- Background-Output
- NYOJ 组合数 32(DFS)
- POJ 题目2253 Frogger(最短路变形)
- 使用Rational Rose来绘制UML图