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;
}
}