C++ boost::lexical_cast

1、 lexical_cast是boost中的一个库, 主要用于数值与字符串的相互转换。boost 的 lexical_cast 能把字符串转成各种 c++ 内置类型,需要包含头文件:

#include <boost/lexical_cast.hpp>
using namespace boost;

2、lexical_cast库进行“字面量”转换,类似于C语言中的atoi函数,可以进行字符串、整数/浮点数之间的转换。使用格式为:

在这里插入图片描述

T是数据类型或模板template 自定义(实例化才知道的类型)

3、使用lexical_cast时要注意,要转换成数字的字符串只能有数字和小数点,不能出现字母(表示指数的e/E除外)或其他非数字字符,也就是说,lexical_cast不能转换如“123L”、“0x100”这样c++语法许可的数字字面量字符串。

int value=boost::lexical_cast(“123”)
float value=boost::lexical_cast(“1.2”)

4、当lexical_cast无法执行转换操作时会抛出异常bad_lexical_cast

terminate called after throwing an instance of ‘boost::exception_detail::clone_impl<boost::exception_detail::error_info_injectorboost::bad_lexical_cast >’
what(): bad lexical cast: source type value could not be interpreted as target

例如 atoi(“2.5”)的值为2,而boost::lexical_cast(“2.5”)则会抛出boost::bad_lexical_cast的异常,因此我们需要用try/catch保护转换。

try
{
int i = boost::lexical_cast(“12.3”);
}
catch (boost::bad_lexical_cast& e)
{
cout << e.what() << endl;
}

5、例如在STL库中,我们可以通过stringstream来实现字符串和数字间的转换:

int i = 0;
stringstream ss;
ss << “123”;
ss >> i;

但stringstream是没有错误检查的功能,例如对如如下代码,会将i给赋值为12.

ss << “12.3”;
ss >> i;

为了解决这一问题,可以通过boost::lexical_cast来实现数值转换:

int i = boost::lexical_cast(“123”);
double d = boost::lexical_cast(“12.3”);

注意!
读取文本文件时可能字符串后面会有“\r”或者"\n"标识符,需要使用trim函数去掉

猜你喜欢

转载自blog.csdn.net/weixin_41169280/article/details/110000325
今日推荐