#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/assert.hpp>
using namespace boost;
using namespace std;
template<typename T>
bool num_valid(const char* str)
{
try
{
lexical_cast<T>(str); //尝试转换数字
return true;
}catch(bad_lexical_cast&){
return false;
}
}
class demo_class
{
friend std::ostream& operator<<(std::ostream& os,const demo_class& x)
{
os << "demo_class's Name";
return os;
}
};
int main( int argc,char **argv)
{
/*常用操作*/
int x = lexical_cast<int>("100");
long y = lexical_cast<long>("2000");
float pai = lexical_cast<float>("3.14159e5");
double e = lexical_cast<double>("2.71828");
cout << x << y << pai << e << endl;
string str = lexical_cast<string>(456);;
cout << str << endl;
cout << lexical_cast<string>(0.618) << endl;
cout << lexical_cast<string>(0x10) << endl;
/*抛出异常*/
try
{
cout << lexical_cast<int>("0x100");
cout << lexical_cast<double>("helloworld");
cout << lexical_cast<bool>("false");
cout << lexical_cast<long>("1000L");
}catch (bad_lexical_cast& e)
{
cout <<"error:" << e.what()<< endl;
}
/*验证字符串的合法性*/
assert(num_valid<double>("3.14"));
assert(!num_valid<int>("3.14"));
assert(num_valid<int>("65535"));
cout << lexical_cast<string>("demo_class") << endl;
return (0);
}
/*注意:
*1.lexical_cast转换成数字的字符串只能有数字和小数点,不能出现除(表示e/E除外)字母或其他非数字字符
*2.它不支持高级的格式控制,如有需要应使用std::stringstream或者boost::format
*3.可以转换bool类型,不能使用true/false.只能使用1或0
*4.*/
/*对转换对象的要求:
* 1.转换起点对象是可流输出的,即定义了operator<<;
* 2.转换终点对象是可流输入的,即定义了operator>>;
* 3.转换终点对象必须是可缺省构造和可拷贝的
* */
boost库之字符串与文本处理——lexical_cast
最新推荐文章于 2021-05-18 15:11:33 发布