程序中,数据的强制转换很多,作为C++程序员,不能拥有像Convert.ToInt16()这么便捷的操作,往往我们使用std::atoi,atof,但是这种转换缺少异常捕获,有时候,我们还必须自己写很多检测的代码。boost提供一个lexical_cast,非常方便。下面是我的一个例子。
#include <boost/lexical_cast.hpp>
#include <boost/xpressive/xpressive_dynamic.hpp>
using namespace boost;
const int bit_field = 1;
const int int_field = 2;
const int bigint_field = 3;
const int float_field = 4;
const int double_field = 5;
const int time_field = 6;
void lexicalTest(int type, std::string data)
{
try
{
if (type == bit_field)
{
bool b_data = lexical_cast<bool>(data);
cout << type << ", test is:" << b_data << endl;
}
else if (type == int_field)
{
int32_t int32_data = lexical_cast<int32_t>(data);
cout << type << ", test is:" << int32_data << endl;
}
else if (type == bigint_field)
{
int64_t int64_data = lexical_cast<int64_t>(data);
cout << type << ", test is:" << int64_data << endl;
}
else if (type == float_field)
{
float float_data = lexical_cast<float>(data);
cout << type << ", test is:" << float_data << endl;
}
else if (type == double_field)
{
double double_data = lexical_cast<double>(data);
cout << type << ", test is:" << double_data << endl;
}
else if (type == time_field)
{
using namespace boost::xpressive;
cregex reg = cregex::compile("[12]\\d{3}\\+(0\\d|1[0-2])\\+([0-2]\\d|3[01])\\+([01]\\d|2[0-3])\\+[0-5]\\d\\+[0-5]\\d");
// time_t time_data = lexical_cast<time_t>(data);
if (regex_match(data.c_str(), reg))
{
cout << "regex_match sucessed!" << endl;
}
else
{
cout << data << " not match time typedef" << endl;
}
// cout << time_data << endl;
}
}
catch (bad_lexical_cast &e)
{
cout << data << "convert to type:" << type << " failed, reason:" << e.what() << endl;
}
}
int main()
{
std::string data = "4294967296";
// std::string data = "2016+12+21+08+23+13";
// lexicalTest(1,data);
// lexicalTest(2,data);
// lexicalTest(3,data);
// lexicalTest(4,data);
// lexicalTest(5,data);
// lexicalTest(6,data);
}
因为我的时间类型字符串是内部定义,所以我使用regex_match,
补充:
如果有这样子的定义:
uint8_t data=3;
std::string strData=boost::lexical_cast(data);
试着输出:
cout<<"data is:"<<strData<<endl;
是的,你发现了什么都没有,今天我还纳闷了,我以为boost这个是不支持的,后来我试了一下使用int16,
没有错,你使用uint8_t ,int8_t都不能够得到正确的答案,所以我把字段修改成了Int
具体原因有待后续发现