如何使用boost对各个类型进行转化

时间:2022-09-09 07:31:44

boost 的编译,如果不考虑其的裁剪也很简单,只需要运行下面的命令,耐心等待,就能完成编译了。

bjam.exe --threading=multi install --without python 

1.#include <boost\lexical_cast.hpp>  这个头文件是用来进行各种转化,最新版本的boost已经改进了很多以前的0x之类的十六进制数是不能进行转化的,最新版本的boost已经没有了这个限制。我写的例子程序如下:

#include <boost\lexical_cast.hpp>
#include<iostream>
#include <string>
void main()
{
	try{
		int x = boost::lexical_cast<int>("100");//字符串转化为int
		double a = boost::lexical_cast<double>("3.3");//字符串转化为double
		std::cout<<a;
		std::string str =boost::lexical_cast<std::string>(333);//int转化为string
		str = boost::lexical_cast<std::string>(0x333);
		std::cout<<str<<std::endl;
	}catch(boost::bad_lexical_cast&e)
	{
		std::cout<<e.what()<<std::endl;
	}
	
}

boost中的format方法实现格式化输入和输出,我写的例子程序如下:

#include <boost\lexical_cast.hpp>
#include<iostream>
#include <string>
#include<boost/format.hpp>
void main()
{
	std::cout<<boost::format("%d")%3;
	boost::format fom("%d");
	fom%3;
	std::string str = fom.str();
	boost::format form2("%05d");
	form2%3;
	str = form2.str();
}