虽然早就听过Boost,也早就已经下了一个收藏了,可一直没有用,呵呵,这回有时间了,可以好好学习一下了
原来以为是必须要编译成lib才行,所以一直都是找编译的方法,终于在stlchina上找到一篇文章,也是boost入门的,说是不编译也能用,只有python,regex才用编译,打开src一看,都是templete,看来只要include就能用。
这样,解压了,只有100M,可如果都编译了,会占1G,不过,删了obj ,会少一半。暂时还不学python和c++和连接编程。而且还在学Lua,可能,python会暂时休息一会吧。
不费话了,设置了include directory后,写了一个最简单的:lexical_cast<>(),用来实现string和数据之间的转换。类似C库中的atoi()之类的函数。
#pragma warning (disable:4819)
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
int main(int argc, char *argv[])
{
using boost::lexical_cast;
int num=lexical_cast<int>("123");
double num2=lexical_cast<double>("123.12");
std::string str=lexical_cast<std::string>(12345);
std::cout<<num<<std::endl;
std::cout<<num2<<std::endl;
std::cout<<str<<std::endl;
return 0;
}
作为一个有工业级强度的库,当然对错误的处理是少不了的,如果转换错误,则会抛出一个异常:boost::bad_lexical_cast
看这个代码:
#pragma warning (disable:4819)
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
int main(int argc, char *argv[])
{
int num=0;
try
{
//bad lexical cast: source type value could not be interpreted as target
num=lexical_cast<int>("abcd");
}
catch (boost::bad_lexical_cast& e)
{
std::cout<<e.what()<<std::endl;
return 1;
}
return 0;
}
最后,小说一下原理,其实lexical_cast就是对stringstream的一个封装,用一个stringstream做中介,实现转换。
OK,第一课过去了。明天要下一课!