boost的字符串处理函数——format

来源:http://www.cnblogs.com/TianFang/archive/2013/02/04/2891501.html


boost::format的格式一般为:
    boost::format( "format-string ") % arg1 % arg2 % ... % argN ;
    注意这里没有示例对象,format-string代表需要格式化的字符串,后面用重载过的%跟参数

1.format占位符的使用 (占位符 是 从 1 开始的,不是从 0 开始的)
    std::cout<<boost::format("%1% \n %2% \n %3%" )%"first"%"second"%"third";
    上面例子中%X%表示占位符,%1%就是第一个占位符,%2%就是第二个,后面类推,
    再后面的%"xxx"就对应着每个占位符,也就是说如果我们写成:
    std::cout<<boost::format("%2% \n %1% \n %3%" )%"first"%"second"%"third";

    将会输出
    second
    first
    third

    当然我们也可以分开写,比如:
    boost::format fmt("%2% \n %1% \n %3%" );
    fmt %"first";
    fmt %"second";
    fmt %"third";

2.format的C语言形式
    你可以这样通过变量格式化,这与int a=5;printf("%d",a);是一个道理,不同的是format是对字符的格式化而不包含输出。
    int a=5;
    int b=6;
    std::cout<< boost::format("%1% %2%" )%a%b;

// 方式一 
cout << boost::format("%s") % "输出内容" << endl; // 方式二 
std::string s; 
s = str( boost::format("%s") % "输出内容" ); 
cout << s << endl; // 方式三 
boost::format formater("%s"); 
formater % "输出内容"; 
std::string s = formater.str(); 
cout << s << endl; // 方式四 
cout << boost::format("%1%") % boost::io::group(hex, showbase, 40) << endl; 
/*三、boost::format新的格式说明符%{nt}当n是正数时,插入n个绝对制表符cout << boost::format("[t]")  << endl;%{nTX}使用X做为填充字符代替当前流的填充字符(一般缺省是一个空格)cout << boost::format("[T*]")  << endl;*/cout<<boost::format("[%5t] Test %5t* ");
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <boost/format.hpp>
#include <iomanip>
using namespace boost;
using namespace std;
using boost::io::group;
/*format类摘要
namespace boost {template<class charT, class Traits=std::char_traits<charT> > 
class basic_format 
{
public:typedef std::basic_string<charT, Traits> string_t;typedef typename string_t::size_type     size_type;basic_format(const charT* str);basic_format(const charT* str, const std::locale & loc);basic_format(const string_t& s);basic_format(const string_t& s, const std::locale & loc);basic_format& operator= (const basic_format& x);void clear(); // reset buffersbasic_format& parse(const string_t&); // clears and parse a new format stringstring_t str() const;size_type size() const;// pass arguments through those operators :template<class T>  basic_format&   operator%(T& x);  template<class T>  basic_format&   operator%(const T& x);// dump buffers to ostream :friend std::basic_ostream<charT, Traits>& operator<< <> ( std::basic_ostream<charT, Traits>& , basic_format& ); // Choosing which errors will throw exceptions :unsigned char exceptions() const;unsigned char exceptions(unsigned char newexcept);// ............  this is just an extract .......
}; // basic_formattypedef basic_format<char >          format;
typedef basic_format<wchar_t >      wformat;// free function for ease of use :
template<class charT, class Traits> 
std::basic_string<charT,Traits>  str(const basic_format<charT,Traits>& f) {return f.str();
}} // namespace boost*/
/*格式化语法:* 1.%05d:输出宽度为5的整数,不足位用0填充* 2.%-8.3f:输出左对齐,总宽度为8,小数位3位的浮点数* 3.%10s:输出10位的字符串,不足位用空格填充* 4.%05x:输出宽度为5的大写16进制数,不足位用0填充* 5.%|spec|:与printf格式选项功能相同,但两边增加了竖线分隔,可以更好地区分格式化选项与普通字符* 6.%N%:标记第N个参数,相当于占位符,不带任何奇特的格式化选项** 建议:* 1.format由于要做安全检查工作,性能略差,约比printf慢2到5倍,为了提高format的性能,建议在编程中应该先建立const format对象,然后拷贝这个对象进行格式化操作** 高级功能:* 1.basic_format& bind_arg(int argN,const T& val); //将第argN个参数绑定为val,即使调用clear()也保持不变* 2.basic_format& clear_bind(int argN);    //取消格式化字符串第argN位置的参数绑定* 3.basic_format& clear_binds();   //取消格式化字符串所有位置参数绑定,并调用argN* 4.basic_format& modify_item(int itemN,T manipulator);    //设置格式化字符串第itemN位置的格式化选项,manipulator是一个boost::io::group返回的对象* */
int main( int argc,char **argv)
{cout << format("%s:%d+%d=%d\n")%"sum"% 1%2%(1+2); //经典用法cout << format("%1% %2%") % 36 %37; //简单风格,可以重新排列输出cout << format("(x,y)=(%1$+5d,%2$+5d)\n") %-23 %35;    //精确的格式化,带posix_printf位置提示符format fmt("(%1%+%2%)*%2%=%3%");fmt % 2 % 5;fmt % ((2+5*5));format fmt1("%05d\n%-8.3f\n%10s\n%05x\n");cout << fmt1 %62 %2.236 %" 12345678" %48;cout << fmt.str() << endl;format fmt2("%1% %2% %3% %2% %1%\n");cout << fmt2 %1 %2 %3;fmt2.bind_arg(2,10);cout << fmt2 %1 %3;fmt2.clear();cout << fmt2 % group(showbase,oct,111) % 333;fmt2.clear_binds();fmt2.modify_item(1,group(hex,right,showbase,setw(8),setfill('*')));cout << fmt2 %49 %20 %100;return (0);
}
// 可以延迟使用,顺序不必一致boost::format fmter("%2% %1%");fmter % 36;fmter % 77;cout << fmter << endl;// 输出:77 36// 可重用fmter % 12;fmter % 24;cout << fmter << endl;// 输出:24 12// 可直接转成字符串std::string s = fmter.str();std::string s2 = str( boost::format("%2% %1% %2% %1%")%"World"%"Hello");cout << s << endl << s2 << endl;// 输出:// 24 12// Hello World Hello World// 可以使用printf指示符cout << boost::format("%3.1f - %.2f%%") % 10.0 % 12.5  << endl;// 输出:10.0 - 12.50%// printf指示符里使用N$指定使用第几个参数cout << boost::format("%2$3.1f - %1$.2f%%") % 10.0 % 12.5  << endl;// 输出:12.5 - 10.00%

    std::cout << boost::format("%s:%04d%02d%02d") % "日期"% 2013 % 9 % 28 << std::endl;std::string test("string");std::cout << boost::format("%s") % test<< std::endl;boost::format fmt1("%1% + %2%*%1% = %3%");fmt1 % 2 % 3 % (2+2*3) ;std::cout << fmt1.str() << std::endl;cout << boost::format( "%1% %2%" ) % "Hell" % "Low" << endl;string s1 = boost::str( boost::format( "%2% %1%" ) % "Hell" % "Low" );cout << s1 << endl;wcout << boost::wformat( L"%s %X" ) % L"-1 is" % -1 << endl;wstring s2 = boost::str( boost::wformat( L"%2$s %1$.2f" ) % 3.141592 % L"Version" );wcout << s2 << endl;char text[]="hello";bool is_all_lower = boost::algorithm::all(text, boost::algorithm::is_lower());char output[128];sprintf(output, "<%s> %s in the lower case", text, (is_all_lower? "is": "is not"));cout<<output<<endl;

用boost::format来格式化字符串

在字符串处理中少不了格式化字符串,C++中传统的格式化函数是C语言的sprintf,但它一个很大的问题就是不安全。因此,在stl中引入了stringstream来实现安全格式化,但是stringstream却远不如sprintf来得直观。例如,对如如下代码:

 char text[]="hello";    bool is_all_lower = boost::algorithm::all(text, is_lower());char output[128];sprintf(output, "<%s> %s in the lower case", text, (is_all_lower? "is": "is not")); 
如果把最后两句format的函数用stringstream来写的话,可读性是远不如sprintf的。
stringstream output;
output << "<" << text << "> "<< (is_all_lower)? "is": "is not")<< " in the lower case"; 
boost引入了一个提供类似.net中的string.format的方式提供格式化字符串的函数,用它来格式化的话就是如下形式:
boost::format fmt = boost::format("<%s> %s in the lower case") % text % (is_all_lower? "is": "is not");
string output = fmt.str(); 

前面的例子中演示的是C风格的格式化字符串,boost.format也提供了类似.net风格的格式化字符串方式:

    boost::format fmt = boost::format("<%1%>%2% in the lower case") % text % (is_all_lower?"is": "is not");
    cout << fmt << endl;

这种方式更容易看到参数在格式化字符串中的位置,推荐这种形式。不过它的起始坐标是1而不是0,用惯了.net的string.format的朋友需要注意下。

格式化控制

格式化语法为: [ N$ ] [ flags ] [ width ] [ . precision ] type-char。也提供了C语言和.net两种风格。

    //传统c语言风格
    cout << boost::format("\n\n%s"
            "%1t
十进制
= [%d]\n"
            "%1t
格式化的十进制 = [%5d]\n"
            "%1t
格式化十进制,前补'0' = [%05d]\n"
            "%1t
十六进制 = [%x]\n"
            "%1t
八进制 = [%o]\n"
            "%1t
浮点 = [%f]\n"
            "%1t
格式化的浮点 = [%3.3f]\n"
            "%1t
科学计数 = [%e]\n"
            ) % "example :\n" % 15 % 15 % 15 % 15 % 15 % 15.01 % 15.01 % 15.01 << endl;

    //.net
的风格

    cout << boost::format("%1%"
            "%1t
十进制
= [%2$d]\n"
            "%1t
格式化的十进制 = [%2$5d]\n"
            "%1t
格式化十进制,前补'0' = [%2$05d]\n"
            "%1t
十六进制 = [%2$x]\n"
            "%1t
八进制 = [%2$o]\n"
            "%1t
浮点 = [%3$f]\n"
            "%1t
格式化的浮点 = [%3$3.3f]\n"
            "%1t
科学计数 = [%3$e]\n"
            ) % "example :\n" % 15 % 15.01 << endl;

异常处理

既然boost.format函数是用来代替sprintf的,那么自然就得有异常处理的功能,而不是像sprintf那样死给你看。boost.format的处理方法是抛异常,它在如下两种情况家会抛异常:

  1. format字符串非法
  2. format绑定非法

如下代码演示了这两种情形:

try{boost::format("<%3");}catch(std::exception& err){cout << err.what() << endl;}boost::format fmt = boost::format("<%3%> %2% in the lower case") % text % (is_all_lower? "is": "is not");try{cout << fmt << endl;}catch(std::exception& err){cout << err.what() << endl;}

封装

boost.format是以一个对象,而不是函数来实现的,导致其使用和异常处理起来要麻烦不少,不过,利用c++11的可变参数模板的语法还是可以很容易把它封装成一个可变参数的函数的形式:

    string string_fromat(constchar*format, …)

需要定义三个重载版本:

    template<classTFirst>
    void string_format(boost::format&fmt, TFirst&& first)
    {
        fmt % first;
    }

    template<classTFirst,class... TOther>
    void string_format(boost::format&fmt, TFirst&& first,TOther&&... other)
    {
        fmt % first;
        string_format(fmt, other...);
    }

    template<classTFirst,class... TOther>
    string string_format(constchar*format, TFirst&& first,TOther&&... other)
    {
        boost::format fmt(format);
        string_format(fmt, first,other...);
        return fmt.str();
    }

现在就可以这么用了:

    auto output = string_format("<%1%> %2% in the lower case", text, (is_all_lower? "is":"is not"));

所有的异常也都会在该函数中抛出,虽然效率上相对低点,但用起来要舒服点。





本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/496881.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

GIS单词汇总

Projection: Transverse_Mercator 墨卡托投影 false_easting: -3457147.813600 东伪偏移 false_northing: 0.000000 北纬偏移 central_meridian: 121.464423 中央子午线 scale_factor: 1.000000 比例因子 latitude_of_origin: 0.000000…

掌控谈话~谈价格的秘诀

很多谈判的内容是&#xff0c;一方提价很高&#xff0c;不然就不合作&#xff1b;一方有钱但是没有那么多钱&#xff0c;希望能够以合理的价格达成合作。这时候的谈判就是一个谈价格的过程。 这时候&#xff0c;要点是&#xff0c; 1.设定自己的心理价格&#xff0c;最好精确…

C++学习之路 | PTA乙级—— 1049 数列的片段和 (20 分)(精简)

1049 数列的片段和 (20 分) 给定一个正数数列&#xff0c;我们可以从中截取任意的连续的几个数&#xff0c;称为片段。例如&#xff0c;给定数列 { 0.1, 0.2, 0.3, 0.4 }&#xff0c;我们有 (0.1) (0.1, 0.2) (0.1, 0.2, 0.3) (0.1, 0.2, 0.3, 0.4) (0.2) (0.2, 0.3) (0.2, 0.3…

Boost学习之正则表达式--regex

来源&#xff1a;http://blog.chinaunix.net/uid-21222282-id-1829265.html 来源&#xff1a;http://www.cnblogs.com/undermoon/archive/2009/11/30/1613508.html 来源&#xff1a;http://blog.csdn.net/guyulongcs/article/details/7838753 来源&#xff1a;http://blo…

(转载)做好一个系统分析师、项目经理75条准则(一)

(转载)做好一个系统分析师、项目经理75条准则(一) 1. 你们的项目组使用源代码管理工具了么&#xff1f; 应该用。VSS、CVS、PVCS、ClearCase、CCC/Harvest、FireFly都可以。我的选择是VSS。 2. 你们的项目组使用缺陷管理系统了么&#xff1f; 应该用。ClearQuest太复杂&#…

智能的源泉,大脑从何而来?

作者&#xff1a;谢平 中国科学院大学教授引言&#xff1a;人类的神奇常常归结于一个智慧的大脑以及贯穿于其中的无比复杂的神经网络&#xff0c;并认为这源自上帝之手&#xff0c;但其实它并不是无中生有的&#xff0c;而是自然演化的产物&#xff0c;虽然是一个无与伦比的杰作…

掌控谈话~校准问题

当谈判即将破裂&#xff0c;怎么办&#xff1f; 你想这样&#xff0c;对方想那样&#xff0c;最后对方直接想要放弃谈判&#xff0c;应该怎么做&#xff1f; 其实很简单&#xff1a;对方处于“不相信”的状态。他们不认为谈判能得到结果。并不是因为没得谈而放弃&#xff0c;…

C++学习之路 | PTA乙级—— 1050 螺旋矩阵 (25 分)(精简)

1050 螺旋矩阵 (25 分) 本题要求将给定的 N 个正整数按非递增的顺序&#xff0c;填入“螺旋矩阵”。所谓“螺旋矩阵”&#xff0c;是指从左上角第 1 个格子开始&#xff0c;按顺时针螺旋方向填充。要求矩阵的规模为 m 行 n 列&#xff0c;满足条件&#xff1a;mn 等于 N&#x…

站在巨人的肩膀上,C++开源库大全

来源&#xff1a;http://blog.csdn.net/chen19870707/article/details/40427645 程序员要站在巨人的肩膀上&#xff0c;C拥有丰富的开源库&#xff0c;这里包括&#xff1a;标准库、Web应用框架、人工智能、数据库、图片处理、机器学习、日志、代码分析等。 值得学习的C语言开…

C#中注释的方法

/*......*/ 试用于大段代码的注释 // 一般注释 /// XML注释 ----------------------养成给代码写注释的好习惯 转载于:https://www.cnblogs.com/williamlyf/archive/2008/04/04/1137740.html

物联网技术在智能医疗领域的应用与发展

来源&#xff1a; 传感器技术应对人口结构高龄化所带来的长期照护需求&#xff0c;各国政府纷纷拟定政策&#xff0c;希望利用Wi-Fi、蓝牙、3G、GPS及RFID等物联网技术&#xff0c;架构起移动式医疗网络;且在远距照护等议题发酵下&#xff0c;也带动医疗产业结合物联网进入下一…

掌控谈话~确保执行

谈判成功了&#xff0c;但是谈判结果却没有执行&#xff0c;那么谈判也是失败的。 谈判结束的时候&#xff0c;执行结果可以从言语&#xff08;7%&#xff09;、语调&#xff08;38%&#xff09;、肢体语言与表情&#xff08;55%&#xff09;看出来。即使是言语上是达成了共同…

xmlHttpRequest无刷新验证用户名

现在好多网站上的注册都用了无刷新验证用户名,这种效果咋看感觉很复杂很难实现,其实它里面用到了Ajax中的核心xmlHttpRequest这个类,如果只是单单想实现这个效果,压根就不用引用Ajax.Net中的组件,因为感觉有点大材小用,下面是具体实现这种效果的方法,希望能给初学Ajax的朋友带来…

C++学习之路 | PTA乙级—— 1051 复数乘法 (15 分)(精简)

1051 复数乘法 (15 分) 复数可以写成 (ABi) 的常规形式&#xff0c;其中 A 是实部&#xff0c;B 是虚部&#xff0c;i 是虚数单位&#xff0c;满足 i ​2 ​​ −1&#xff1b;也可以写成极坐标下的指数形式 (Re ​(Pi) ​​ )&#xff0c;其中 R 是复数模&#xff0c;P 是辐角…

如何理解和评价机器学习中的表达能力、训练难度和泛化性能

来源&#xff1a; Eric Jang 的个人博客非常感谢王家兴 (Jiaxing Wang) 把这个博客文章翻译成中文。当我在阅读机器学习相关文献的时候&#xff0c; 我经常思考这项工作是否&#xff1a;提高了模型的表达能力&#xff1b;使模型更易于训练&#xff1b; 提高了模型的泛化性能。在…

数据库连接 未将对象引用到实例

原来的连接server.;databasetest;uidsa;pwdsa;解决方案"Data Source数据库地址;Initial Catalog数据库名;User ID用户名;Password密码";不知道原因&#xff0c;谁知道告诉我&#xff01;谢谢&#xff01; 转载于:https://www.cnblogs.com/cangqiong/archive/2008/04/…

C++学习之路 | PTA乙级—— 1052 卖个萌 (20 分)(精简)

1052 卖个萌 (20 分) 萌萌哒表情符号通常由“手”、“眼”、“口”三个主要部分组成。简单起见&#xff0c;我们假设一个表情符号是按下列格式输出的&#xff1a; 左手[右手] 现给出可选用的符号集合&#xff0c;请你按用户的要求输出表情。 输入格式&#xff1a; 输入首先在前…

谷歌公布72位量子比特处理器,吹响量子霸权冲锋号

作者&#xff1a;杨晓凡谷歌量子 AI 实验室今天发布了新的 72 位量子比特的量子处理器 Bristlecone。虽然目前还没有看到具体的实验结果&#xff0c;但这块芯片的未来有很大潜力&#xff0c;很有可能达成量子计算领域内的重要里程碑。谷歌量子 AI 实验室&#xff08;Google Qua…

oracle查询语句大全(oracle 基本命令大全一)

来源&#xff1a;http://www.jb51.net/article/40467.htm 1.create user username identified by password;//建用户名和密码oracle ,oracle 2.grant connect,resource,dba to username;//授权 grant connect,resource,dba,sysdba to username; 3.connect username/password/…

掌控谈话~拔刺(说出你对我的指控)

适用于发生重大错误的时候&#xff0c;尤其是责任都在自己身上的情况。 在出现重大错误的时候&#xff0c;在谈话的开始&#xff0c;就直接讲明错误的具体情况&#xff0c;给对方带来的损失&#xff0c;把问题分析透彻&#xff0c;主动承认自己的各种问题和错误&#xff0c;主…