简述


编程中经常会遇到需要到使用的数据进行格式化的地方,如生成记录日志的字符串,生成发送到网络的完整数据等。

可能需要对int, string, char等进行格式化,常用的方法包括 snprintf, std::string, std::stringstream, boost::format等。

snprintf支持c语言,可能是这几种方式中效率最高的,它们之间的效率对比可以参考 Comparing the performance of a sequence of several generators 。

但对于效率要求不是非常严苛的场合下,使用其他方法可能会更加方便,这里就要介绍boost::format。

boost::format使用


如果你已经在使用boost库,使用format进行格式化将是一件非常简单的事情。

如前所述,format没有snprintf快,但它是类型安全的。它使用streams构建输出,所以不会存在内存溢出的情况。

format有两种使用风格,一种类似于 printf,另一种使用占位符,类似于c#。

浮点数格式

直接上代码:

const double almostpi = 22.0 / 7.0;// Printf
printf("Pi is %f\n", almostpi);// Boost format with printf syntax
boost::format printf_formatting("Pi is %f\n");
std::cout << printf_formatting % almostpi;// Boost format with positional syntax
boost::format position_formatting("Pi is %1%\n");
std::cout << position_formatting % almostpi;// Output:
// Pi is 3.142857
// Pi is 3.142857
// Pi is 3.14286

显然,format的使用与printf类似,使用 %f 格式化一个浮点数,默认的精度是6位小数。

使用更大的数据可以验证这个结论,如:

const double almostpi = 22.0 / 7.0;
const double distancetosun = 149600000000.0;    // meters
const double earthorbitlength = 2 * almostpi * distancetosun;// Printf
printf("Earth orbit distance is %f meters\n", earthorbitlength);// Boost format with printf syntax
boost::format printf_formatting("Earth orbit distance is %f meters\n");
std::cout << printf_formatting % earthorbitlength;// Boost format with positional syntax
boost::format position_formatting("Earth orbit distance is %1% meters\n");
std::cout << position_formatting % earthorbitlength;// Output:
// Earth orbit distance is 940342857142.857180 meters
// Earth orbit distance is 940342857142.857180 meters
// Earth orbit distance is 9.40343e+011 meters

使得 %1% 占位符时,当数值较大时,会使用科学计数法(大概6-7个字符长度时会使用)。

关于科学计数法

一般而言,只有在使用占位符时,且数值较大时才会转换为科学计数法。如:

boost::format scinotation("Do we use scientific? '%1%'\n");// %llu时也会显示科学计数法for (size_t n=0; n<15; ++n)
{double value = 1 * pow(10, n) + 0.5;std::cout << scinotation % value;
}// Output:
// Do we use scientific? '1.5'
// Do we use scientific? '10.5'
// Do we use scientific? '100.5'
// Do we use scientific? '1000.5'
// Do we use scientific? '10000.5'
// Do we use scientific? '100001'
// Do we use scientific? '1e+006'
// Do we use scientific? '1e+007'
// Do we use scientific? '1e+008'
// Do we use scientific? '1e+009'
// Do we use scientific? '1e+010'
// Do we use scientific? '1e+011'
// Do we use scientific? '1e+012'
// Do we use scientific? '1e+013'
// Do we use scientific? '1e+014'

另外,在实际使用中,如果使用了不匹配的标记符时,如使用了%llu, 而实际数值却是double时,也会以科学计数法显示。

可以使用 %e 显示指定以科学计数法显示。

格式控制

格式控制的语法为:%[N$][flags][width][.precision]type-char。如:

// Printf
printf("Pi is '%10.2f'\n", almostpi);// Boost format with printf syntax
boost::format printf_formatting("Pi is '%10.2f'\n");
std::cout << printf_formatting % almostpi;// Boost format with positional syntax
boost::format position_formatting("Pi is '%1$10.2f'\n");
std::cout << position_formatting % almostpi;// Output:
// Pi is '      3.14'
// Pi is '      3.14'
// Pi is '      3.14'

常用示例


简单的使用方式,可以直接输出想要的内容:

// 直接输出
cout << boost::format("%s") % "this is what i want" << endl; // 结合 string
string s;
s = str(boost::format("%s") % "this is what i want");
cout << s << endl;// 使用 formater
boost::format fmt("%s");
fmt % "this is what i want";
string s = fmt.str();
cout << s << endl;// 占位符
cout << boost::format("%1%") % "this is what i want" << endl;

异常处理


format 异常时会throw 异常信息,所以要使用try语句块处理异常,否则程序默认会终止。如:

try
{cout << boost::format("%d%d") % 1 << endl;
}
catch (std::exception const &e)
{cout << e.what() << endl;
}
catch (...)
{cout << "format error" << endl;
}// output
// boost::too_few_args: format-string refered to more arguments than were passed

参考资料:

Boost::format (and wformat) examples – numbers: int, float, double
Comparing the performance of a sequence of several generators
浅尝boost之format

boost format使用详解相关推荐

  1. python3 format函数_Python学习教程:Python3之字符串格式化format函数详解(上)

    Python学习教程:Python3之字符串格式化format函数详解(上) 概述 在Python3中,字符串格式化操作通过format()方法或者f'string'实现.而相比于老版的字符串格式化方 ...

  2. format函数_Python学习教程:Python3之字符串格式化format函数详解(上)

    Python学习教程:Python3之字符串格式化format函数详解(上) 概述 在Python3中,字符串格式化操作通过format()方法或者f'string'实现.而相比于老版的字符串格式化方 ...

  3. access中的Format用法详解

    access中的Format用法详解 Format$(Now,"EEOA") 只要这么一句~~~~~就可以得到" 二○○六年五月二十六日" ---------- ...

  4. python字符串format方法参数解释,一文秒懂!Python字符串格式化之format方法详解

    一文秒懂!Python字符串格式化之format方法详解 一文秒懂!Python字符串格式化之format方法详解 format是字符串内嵌的一个方法,用于格式化字符串.以大括号{}来标明被替换的字符 ...

  5. python format用法详解

    format 基本语法是通过 {} 和 : 来代替以前的 % . format 函数可以接受不限个参数,位置可以不按顺序. format基本用法 "Hello {0} {1}".f ...

  6. python3 format函数 详解

    python3 format函数 详解 '三岁和你学编程,最白话的语言,最简单的理解,和你一起学习python' 文章目录 python3 format函数 详解 我怎么来??? -- 输出报错啦 我 ...

  7. String.format()方法详解

    String.format()方法详解 前言: String.format()作为文本处理工具,为我们提供强大而丰富的字符串格式化功能,这里根据查阅的资料做个学习笔记,整理成如下文章,供后续复习查阅. ...

  8. Python基础之格式化输出函数format()功能详解

    之前发过一篇文章:Python基础之常用格式化输出字符详解 但是呢,有时候我们需要用到多个%的时候,用这个就很不方便了,比如数错%数量或者一 一对应的时候... 这里补充一个字典方式的格式化输出字符的 ...

  9. Win32开发之Format MessageBox 详解

    本文介绍在Windows程序开发中的MessageBox详解.   我们在在Windows程序设计中经常会涉及到一个格式化消息框,其代码如下: #include <windows.h> # ...

  10. Boost::split用法详解

    工程中使用boost库:(设定vs2010环境) 在Library files加上 D:\boost\boost_1_46_0\bin\vc10\lib 在Include files加上 D:\boo ...

最新文章

  1. Android 使用NineOldAndroids实现绚丽的ListView左右滑动删除Item效果
  2. gitlab 安装_Linux学习14CentOS安装gitlab环境
  3. Redis学习之集群(五)
  4. 【渝粤题库】广东开放大学 标准的研制与编制 形成性考核
  5. 惊了!最通俗易懂的Djongo入门竟然在这里!
  6. 不安装cudnn可不可以_关于CUDA和cuDNN的安装
  7. 清北学堂模拟赛day7 错排问题
  8. RabbitMQ使用guest登录报错:User can only log in via localhost
  9. CSS安全字体的写法
  10. 优思学院|2021中质协六西格玛绿带考题及答案
  11. asterisk的sip.conf配置
  12. 树莓派 之 USB摄像头安装和使用
  13. 团队作业第二次—项目选题报告
  14. 解决无线网络不稳定的两个方案几个方法
  15. 基于RSA+AES 软件授权License
  16. 学习python必逛的几个网站,没看过别说你想学好python
  17. ARPANET的设计思想 (分组交换)
  18. C 语言跳动的心(可变色版本)
  19. 计算机中丢失quartz dll,win10系统提示缺少quartz.dll文件的解决方法
  20. linux yum安装iscsi,CentOS 安装配置iscsi共享存储

热门文章

  1. 查看往年CET46级成绩考试记录
  2. java 免费 cms建站系统_最受欢迎免费开源CMS建站系统排行榜
  3. 【USACO题库】5.2.1 Snail Trails蜗牛的旅行
  4. 云等保安全合规解决方案
  5. 【操作系统】分区分配算法(首次适应算法、最佳适应算法)C语言
  6. vs2019 vs2022番茄助手重新安装失败问题处理
  7. 打开 Windows 10 默认共享
  8. win2003终端服务器超出了最大允许连接数解决方案
  9. ROMS模式RNT工具包的应用(弃用)
  10. Android开放root权限