boost::lexical_cast为数值之间的转换(conversion)提供了一揽子方案,比如:将一个字符串"123"转换成整数123,代码如下:
- string s = "123";
- int a = 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
- 06 using namespace std;
- 07 using namespace boost;
- 08
- 09 int main()
- 10 {
- 11 string s = "123";
- 12 int a = lexical_cast<int>(s);
- 13 double b = lexical_cast<double>(s);
- 14
- 15 printf("%d/r/n", a + 1);
- 16 printf("%lf/r/n", b + 1);
- 17
- 18 try
- 19 {
- 20 int c = lexical_cast<int>("wrong number");
- 21 }
- 22 catch(bad_lexical_cast & e)
- 23 {
- 24 printf("%s/r/n", e.what());
- 25 }
- 26
- 27 return 0;28 }
如上程序实现字符串"123"到整数、双精度实数的转换(为了防止程序作弊,我们特意让它将值加1),结果输出如图4-19所示。
光盘导读
该项目对应于光盘中的目录"/ch04/LexicalCastTest"。
===============================
以上摘自《把脉VC++》第4.6.2小节的内容 ,转载请注明出处。
如果你想与我交流,请点击如下链接加我为好友:http://student.csdn.net/invite.php?u=113292&c=8913f87cffe7d533
from:http://blog.csdn.net/bluejoe2000/article/details/4461421
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!