• boost::format(字符串格式化库)


    这段时间学习boost库的使用,撰文一方面留以备用,另一方面就是shared精神。


    format主要是用来格式化std::string字符串以及配合std::cout代替C语言printf()

    使用format需要#include"boost/format.hpp"

    boost::format的格式一般为:

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


    1.format占位符的使用

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

    std::cout<<boost::format("%2% 
     %1% 
     %3%" )%"first"%"second"%"third";
    将会输出

    second

     first

     third

    当然我们也可以分开写,比如:

        boost::format fmt("%2% 
     %1% 
     %3%" );
        fmt %"first";
        fmt %"second";
        fmt %"third";

    2.format的交互形式

    标题不好,凑合看吧。

    我们还可以很方便的把格式化后的实例赋给std::string,如:
    boost::format fmt("%1%")%"helloworld"; 
    std::string st=fmt.str();

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

    3.format格式化

    格式化语法为: [ N$ ] [ flags ] [ width ] [ . precision ] type-char
    有两种版本:C语言和.net版本,我这里就复制粘贴了一段:
        //传统c语言风格
        cout << boost::format("
    
    %s"
                "%1t 十进制 = [%d]
    "
                "%1t 格式化的十进制 = [%5d]
    "
                "%1t 格式化十进制,前补'0' = [%05d]
    "
                "%1t 十六进制 = [%x]
    "
                "%1t 八进制 = [%o]
    "
                "%1t 浮点 = [%f]
    "
                "%1t 格式化的浮点 = [%3.3f]
    "
                "%1t 科学计数 = [%e]
    "
                ) % "example :
    " % 15 % 15 % 15 % 15 % 15 % 15.01 % 15.01 % 15.01 << endl;
        //.net的风格
        cout << boost::format("%1%"
                "%1t 十进制 = [%2$d]
    "
                "%1t 格式化的十进制 = [%2$5d]
    "
                "%1t 格式化十进制,前补'0' = [%2$05d]
    "
                "%1t 十六进制 = [%2$x]
    "
                "%1t 八进制 = [%2$o]
    "
                "%1t 浮点 = [%3$f]
    "
                "%1t 格式化的浮点 = [%3$3.3f]
    "
                "%1t 科学计数 = [%3$e]
    "
                ) % "example :
    " % 15 % 15.01 << endl;


    boost::format使用还是很不错的,不过效率不尽人意,所以你需要在效率和使用方便两个方面取舍

  • 相关阅读:
    CAP原理、一致性模型、BASE理论和ACID特性
    MyBatis双数据源配置
    MySQL中间件Atlas安装及使用
    MySQL主从切换
    MySQL定时逻辑备份
    MySQL主从搭建
    zabbix监控nginx
    SVN Files 的值“ < < < < < < < .mine”无效。路径中具有非法字符。
    ie8下table的colspan属性与max-with属性的显示错乱问题
    MVC 自定义异常错误页面处理
  • 原文地址:https://www.cnblogs.com/ysherlock/p/7822303.html
Copyright © 2020-2023  润新知