boost::lexical_cast 学习小记

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;
}

测试结果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章