boost之数值转换lexical_cast

boost之数值转换lexical_cast

//字符串转整数
	int  a = atoi("123");
	cout << a << endl;

	//整数转字符串
	char b[64] = {0};
	itoa(16, b, 2);
	cout << b << endl;

	//字符串转浮点数
	double  c = atof("1.23456");
	cout << c << endl;

	//浮点数转字符串
	char d[64] = { 0 };
	gcvt(1.23456, 4, d);//四舍五入
	cout << d<< endl;
  • vs 属性安全检查
    属性页 --> C/C++ -->常规 --> SDL检查设置为否

  • Boost库中lexical_cast为数值之间转换提供一个更好的方案,建议忘掉std诸多函数,直接使用lexical_cast。如果发生了意外,lexical_cast会抛出一个bad_lexical_cast异常,因此程序中需要对其进行try-catch。

  • boost/lexical_cast.hpp中定义了此函数,lexical_cast使用统一接口形式实现任意类型之间的转换,增加了易用性。

#include <iostream>
#include <boost/lexical_cast.hpp>

using namespace std;
using   boost::lexical_cast;//声明,省略boost名字空间前缀
using   boost::bad_lexical_cast;

int main()
{
	
	try
	{
		//字符串转整型
		//int  a = lexical_cast<int>("123");
		int  a = lexical_cast<int>("123efd", 3);
		cout << a << endl;

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

		//浮点数转为字符串
		string   c = lexical_cast<string>("1.23456");
		cout << c << endl;

		//浮点数转为字符串
		string   d = lexical_cast<string>(666);
		cout << d << endl;
	}
	//catch (const std::exception&  e)
	catch (const bad_lexical_cast& e)
	{
		cout << e.what() << endl;
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值