C++ boost库零基础教程(二):boost数值转换

       在STL中有一些列的字符转换函数,例如atoi(), itoa()等,在boost里面只需用一个函数lexical_cast进行转换,lexical_cast是模板方法,使用时需要传入类型。

     使用方法:

            (1)包含头文件 #include <boost/lexical_cast.hpp>

            (2)命名空间  using namespace boost

       例如 字符串转int, 示例代码如下:

        //字符串转整型
	int a = lexical_cast<int>("12");
	int b = lexical_cast<int>("34");
	cout << "a+b = " << a + b << endl;

具体的代码如下:

// boost_01.cpp : 定义控制台应用程序的入口点。
//

/*
boost数值转换, 可以转换所有类型,比atoi,itoa这些函数方便
*/

#include "stdafx.h"
#include <boost/lexical_cast.hpp>
#include <iostream>

using namespace std;
using namespace boost;

int main()
{
	//字符串转整型
	int a = lexical_cast<int>("12");
	int b = lexical_cast<int>("34");
	cout << "a+b = " << a + b << endl;

	//字符串转浮点型
	float f = lexical_cast<float>("1.23456");
	cout << f << endl;

	//浮点数转字符串
	string str = lexical_cast<string>("3.141592655");
	cout << str << endl;

	//对于线面这种,例如字符串是 "789edc",这种会转换失败
	//需要用try...catch, 实际上所有的转换都应该用try...catch
	//使用bad_lexical_cast异常捕获
	try 
	{
		//下面这种换换会出异常
		//int err = lexical_cast<int>("789edc");

		//指定转换的长度,例如转换前两位
		int err = lexical_cast<int>("789edc", 2);
		cout << err << endl;
	}
	//catch(const std::exception& e)
	catch (const bad_lexical_cast& e)
	{
		cout << e.what() << endl;
	}

	system("pause");
    return 0;
}

              某些转换可能会失败,最好用try...catch语句包含,不然程序会出异常,例如“789edc”这种在转整型时如果未指明转换的长度,就会抛异常,

 

       boost的异常类 bad_lexical_cast 的基类是exception, 在项目中应用时最好将lexical_cast的转换语句全部写到try...catch中,避免不必要的异常,程序崩溃。

猜你喜欢

转载自blog.csdn.net/yao_hou/article/details/89812259