Boost库基础-字符串与文本处理(format)

format

#include <boost/format.hpp>
using namespace boost;

 用法:

#include <boost/format.hpp>
using namespace boost;

int main()
{
    cout<< format("%s:%d+%d=%d\n") %"sum" % 1 % 2 % (1+2);
    
    format fmt("(%1% + %2%) * %2% = %3%\n");
    fmt % 2 % 5;
    fmt % ((2 + 5) * 5);
    cout << fmt.str();
}

//结果
sum:1+2=3
(2 + 5) * 5 = 35
  • 代码里第一条语句跟printf()很像,构造函数参数是格式化字符串,使用%x来指定参数的格式,因为参数个数不确定,format模仿了流操作符<<,重载了二元操作费operator% 作为参数输入符,它同样可以串联任意数量的参数,
因此:format(...) % a % b % c 可以理解成 format(...) << a << b << c
  • 后面3条语句演示了另一种用法, 预先创建一个格式化对象,它可以被后面的代码多次用于格式化操作。format对象仍然用操作符%来接受被格式化的参数,可以分多次输入(不必一次给全),但参数的数量必须满足格式化字符串的要求。
类似于 printf("(%d + %d) * %d = %d\n", 2, 5, 5, (2 + 5)*5);

类摘要

format并不是一个真正的类,而是一个typedef,真正的实现是basic_format,它的声明如下:

  • 构造函数可以接受C字符串或std::string,被声明为explicit,我们只能使用显示构造。
  • 成员函数str()返回已经格式化好的字符串。
  • size()获得已格式化好的字符串长度,相当于str().size()。
  • parse()清空format对象内部缓存,并改用一个新的格式化字符串。如果仅仅清空缓存,可以用clear()。
  • 重载了operator%,可以接受待格式化的任意参数。%输入的参数个数必须恰好等于格式化字符串要求都数量,在调用字符串或clear()清空缓冲区之后,则可以再次使用%。
  • 重载流输出操作符。

以下为格式化语法:

除此之外,还增加了新的格式:

%|spec|:两边增加竖线,可以更好区分格式化选项与普通字符

//上图中可以写成这样
format fmt("%|05d|\n%|-8.3f|\n%| 10s|\n%|05X|\n");

%N%:标记第N个参数,相当于占位符,不带任何其他都格式化选项。

高级用法:

//把格式化字符串第argN位置的输入参数固定为val,即使调用clear()也保持不变,除非调用
//clear_bind() 或 clear_binds();
basic_format& bind_arg(int argN,const T& val)

//取消格式化字符串第argN位置的参数绑定
basic_format& clear_bind(int argN)

//取消格式化字符串所有位置的参数绑定,并调用clear()
basic_format& clear_binds();

//设置格式化字符串第itemN位置都格式化选项,manipulator是一个boost::io::group()返回的对象
basic_format& modify_item(int itemN,T manipulator)

//它是一个模板函数,最多支持10个参数,可以设置输入/输出流操纵器以指定格式或输入参数值
boost::io::group(T1 a1,...,Var const& val)

用法:

#include <iostream>
#include <boost/format.hpp>
#include <iomanip>

using namespace boost;
using boost::io::group;

int main()
{
    //声明formatt对象,有三个输入参数,五个格式化选项
    format fmt("%1% %2% %3% %2% %1% \n");

    std::cout << fmt %1 %2 %3;

    //将第二个输入参数固定为数字10
    fmt.bind_arg(2, 10);
    std::cout << fmt %1 %3;

    //清空缓冲,但绑定都参数不变
    fmt.clear();

    //在%操作符中使用group(),指定输入/输出流操纵符第一个参数显示为八进制
    std::cout << fmt % group(std::showbase, std::oct, 111) % 333;

    //清除所有绑定参数
    fmt.clear_binds();

    //设置第一个格式化项,十六进制,宽度为8,右对齐,不足位用*填充
    fmt.modify_item(1, group(std::hex, std::right, std::showbase, std::setw(8), std::setfill('*')));

    std::cout << fmt % 49 % 20 % 100;

	getchar();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wzz953200463/article/details/105126535
今日推荐