1、字符串->数值
#include <boost/lexical_cast.hpp>
#include <iostream>
int main()
{
using boost::lexical_cast;
int a = lexical_cast<int>("123");
double b = lexical_cast<double>("123.12");
std::cout<<a<<std::endl
std::cout<<b<<std::endl;
return 0;
}
2、数值->字符串
#include <boost/lexical_cast.hpp>
#include <string>
#include <iostream>
int main()
{
using std::string;
const double d = 123.12;
string s = boost::lexical_cast<string>(d);
std::cout<<s<<std::endl;
return 0;
}
3、异常
#include <boost/lexical_cast.hpp>
#include <iostream>
int main()
{
using std::cout;
using std::endl;
int i;
try
{
i = boost::lexical_cast<int>("xyz");
}
catch(boost::bad_lexical_cast& e)
{
cout<<e.what()<<endl;
return 1;
}
cout<<i<<endl;
return 0;
}
显然“xyz”并不能转换为一个int类型的数值,于是抛出异常,捕捉后输出“bad lexical cast: source type value could not be interpreted as target”这样的信息。
4、注意事项
lexical_cast依赖于字符流std::stringstream,其原理相当简单:把源类型读入到字符流中,再写到目标类型中,就大功告成。
int d = boost::lexical_cast<int>("123");
相当于
int d;
std::stringstream s;
s<<"123";
s>>d;
5、小结
我们已经体验了boost::lexcial_cast。当然,lexical_cast不仅仅局限于字符串类型与数值类型之间的转换:可在任意可输出到stringstream的类型和任意可从stringstream输入的类型间转换。
;-)
分享到:
相关推荐
boost::lexical_cast用法示例,包含数值转字串,字串转数值以及相应的异常处理代码
你正在使用一个UNIX系统(或者 cygwin),他们将使得构建LuaBind静态库变得很简单.如果 你正在使用 Visual Studio ,很简单的包含 src 目录下的文件到你的工程即可. 构建LuaBind的时候,你可以设定一些选项来使得库更加...
c++通过boost库实现字符串之间与数字之间的
使用flex实现的C语言词法分析,在linux和window下都试过,应该不会有问题,内含编译好的exe文件,直接运行可能会报错,需要将编译器地址放入环境变量
python写一个简易的词法分析器,比上次的代码加上了一个交互界面,此为demo,可以根据这个代码修改成完整的词法分析器。
blackjazz07 conversion/lexical_cast, format hzjboost tuple xuwaters parameter, timer 金庆 python, signals, signals2 zhaohongchao exception, gil luckycat06 interval, math, math/complex number ...
用C++写的C语言词法分析器,vc6.0开发
lexical_analyzer
2 x序列/序列-1.psyexp(每个块〜6分钟)2 x序列/序列-2.psyexp(每个块〜6分钟)1 x sequence-lexical_decision / sequence-1_LD.psyexp(每个块〜2分钟) 1 x sequence-lexical_decision / sequence-2_LD.psyexp...
compiler_lexical_analyzer
boost基本入门使用示例,简单,一看就懂! 部分代码如下: int a = lexical_cast("123"); double b = lexical_cast("123.0123456789"); string s0 = lexical_cast(a);
一个词法编译器。功能描述在help.txt中有说明。
java语法分析程序 主要是用于编译器原理的实践
词汇语义结构的隐喻研究,刘永志,,本文从隐喻,以及隐喻和通感、转喻的联合作用角度来研究词汇的语义结构。作者首先讨论了隐喻(包含通感)的认知模式,以及转喻的
词法编译器,包含.jar的可运行文件,还有NDF流程图
lexical analysis explained
Realisation d'un analyseur lexical en cpp et deux fichier .h
Updated Libraries: Asio, Chrono, Container, Context, Conversion, DateTime, Flyweight, Function, Functional/Factory, Fusion, Geometry, Hash, Interprocess, Intrusive, Lexical Cast, Log, Math, Move, ...
制作一个简易的编译器,能够对于给出的符合文法规则程序代码能进行词法分析、语法分析、语义分析并最终生成汇编代码。