概述
C++程序中数据类型转换是十分常用的操作,本文介绍如何使用boost库来实现数据类型的转换。
lexical_cast
boost中通过boost::lexical_cast一系列模板函数来实现数据类型转换,boost::lexical_cast的头文件为
#include <boost/lexical_cast.hpp>
基本原型定义如下:
namespace boost
{
template <typename Target, typename Source>
inline Target lexical_cast(const Source &arg)
{
Target result;
if (!boost::conversion::detail::try_lexical_convert(arg, result)) {
boost::conversion::detail::throw_bad_cast<Source, Target>();
}
return result;
}
}
基本使用方法
#include<boost/lexical_cast.hpp>
#include <iostream>
int main(int argc,const char* argv[])
{
//字符串转为数值
int n = boost::lexical_cast<int>("520");
std::cout << n <<std::endl;
//字符串转为float
float f = boost::lexical_cast<float>("123.456");
std::cout << f <<std::endl;
//字符串转为double
double d = boost::lexical_cast<double>("3.14159");
std::cout << d << std::endl;
//取前3位字符转换为double
double d1 = boost::lexical_cast<double>("3.14159",3);
std::cout << d1 << std::endl;
//double转为string
std::string s = boost::lexical_cast<std::string>(1.121415926);
std::cout << s <<std::endl;
//16进制数转为string
std::string shex = boost::lexical_cast<std::string>(0x000a);
std::cout << shex << std::endl;
return 0;
}
上面的程序运行结果如下:
[root@sansec fcztest]# ./a.out
520
123.456
3.14159
3.1
1.1214159260000001
10
异常处理
当使用lexical_cast进行数据类型转换时,如果转换错误会抛出异常,因此标准的写法应该再转换中通过try-catch块进行异常处理,如下
#include<boost/lexical_cast.hpp>
#include <iostream>
int main(int argc,const char* argv[])
{
//字符串转为float
float f = 0.0f;
try
{
f = boost::lexical_cast<float>("123.456f");
}
catch(const boost::bad_lexical_cast & e)
{
std::cerr << e.what() << '\n';
}
std::cout << f <<std::endl;
return 0;
}
运行结果如下:
[root@sansec fcztest]# ./a.out
bad lexical cast: source type value could not be interpreted as target
f=0