lexical_cast是boost中的一個庫, 主要用於數值與字符串的相互轉換。
使用起來也很方便,例:
int value=boost::lexical_cast<int>("123")
float value=boost::lexical_cast<float>("1.2")
但是lexical_cast的字符串轉數值功能相比atoi()函數類型檢測更嚴格,
例如 atoi("2.5")的值爲2,而boost::lexical_cast<int>("2.5")則會拋出boost::bad_lexical_cast的異常
因此在使用boost::lexical_cast時一定要捕獲異常。
常見轉換測試如下:
#include "stdafx.h"
#include <string>
#include <boost/lexical_cast.hpp>
#define _LOG(...) {\
do \
{\
printf(##__VA_ARGS__);\
printf("\n");\
} while (0);\
}\
void failedLog(const char *key,const char *castType)
{
_LOG("\"%s\" cast %s value failed", key, castType);
}
void strCastInt(const char *key)
{
try{
_LOG("\"%s\" cast int value= %d", key, boost::lexical_cast<int>(key));
}
catch (boost::bad_lexical_cast e){
failedLog(key, "int");
}
}
void strCastFloat(const char *key)
{
try{
_LOG("\"%s\" cast float value= %.2f", key, boost::lexical_cast<float>(key));
}
catch (boost::bad_lexical_cast e){
failedLog(key, "float");
}
}
void strCastBool(const char *key)
{
try{
_LOG("\"%s\" cast bool value= %d", key, boost::lexical_cast<bool>(key));
}
catch (boost::bad_lexical_cast e){
failedLog(key, "bool");
}
}
void intCastStr(const int &key)
{
try{
_LOG("\"%d\" cast string value= %s", key, boost::lexical_cast<std::string>(key).c_str());
}
catch (boost::bad_lexical_cast e){
failedLog("","string");
}
}
void floatCastStr(const float &key)
{
try{
_LOG("\"%f\" cast string value= %s", key, boost::lexical_cast<std::string>(key).c_str());
}
catch (boost::bad_lexical_cast e){
failedLog("","float");
}
}
void boolCastStr(const bool &key)
{
try{
_LOG("\"%d\" cast string value= %s", key, boost::lexical_cast<std::string>(key).c_str());
}
catch (boost::bad_lexical_cast e){
failedLog("","bool");
}
}
int main()
{
char *key="0";
strCastInt(key);
strCastFloat(key);
strCastBool(key);
_LOG("");
key = "1";
strCastInt(key);
strCastFloat(key);
strCastBool(key);
_LOG("");
key = "2";
strCastInt(key);
strCastFloat(key);
strCastBool(key);
_LOG("");
key = "2.5";
strCastInt(key);
strCastFloat(key);
strCastBool(key);
_LOG("");
key = "";
strCastInt(key);
strCastFloat(key);
strCastBool(key);
_LOG("");
key = "1K";
strCastInt(key);
strCastFloat(key);
strCastBool(key);
_LOG("");
intCastStr(520);
floatCastStr(5.21);
boolCastStr(true);
getchar();
return 0;
}
測試結果: