javasogo 发表于 2013-1-26 13:40:33

万能转换器boost::lexical_cast

boost::lexical_cast为数值之间的转换(conversion)提供了一揽子方案,比如:将一个字符串"123"转换成整数123,代码如下:

[*]strings="123";
[*]inta=lexical_cast<int>(s);
这种方法非常简单,笔者强烈建议大家忘掉std诸多的函数,直接使用boost:: lexical_cast。如果转换发生了意外,lexical_cast会抛出一个bad_lexical_cast异常,因此程序中需要对其进行捕捉。

现在动手
编写如下程序,体验如何使用boost:: lexical_cast完成数值转换。
【程序 4-11】使用boost:: lexical_cast完成对象数值转换

[*]01#include"stdafx.h"
[*]02
[*]03#include<iostream>
[*]04#include<boost/lexical_cast.hpp>
[*]05
[*]06usingnamespacestd;
[*]07usingnamespaceboost;
[*]08
[*]09intmain()
[*]10{
[*]11strings="123";
[*]12inta=lexical_cast<int>(s);
[*]13doubleb=lexical_cast<double>(s);
[*]14
[*]15printf("%d\r\n",a+1);
[*]16printf("%lf\r\n",b+1);
[*]17
[*]18try
[*]19{
[*]20intc=lexical_cast<int>("wrongnumber");
[*]21}
[*]22catch(bad_lexical_cast&e)
[*]23{
[*]24printf("%s\r\n",e.what());
[*]25}
[*]26
[*]27return0;28}
如上程序实现字符串"123"到整数、双精度实数的转换(为了防止程序,我们特意让它将值加1),结果输出如图4-19所示。

http://images.51cto.com/files/uploadimg/20090708/131319535.jpg(点击查看大图)图4-19 运行结果光盘导读
该项目对应于光盘中的目录"\ch04\LexicalCastTest"。
===============================
http://book.vcer.net/images/vcmap-s.gif
以上摘自《把脉VC++》第4.6.2小节的内容,转载请注明出处。
如果你想与我交流,请点击如下链接加我为好友:http://student.csdn.net/invite.php?u=113292&c=8913f87cffe7d533
页: [1]
查看完整版本: 万能转换器boost::lexical_cast