C++ Boost库:字符串格式化 format


C++ Boost库:简介和第一个示例程序
C++ Boost库:数值转换 lexical_cast
C++ Boost库:字符串格式化 format
C++ Boost库:字符串string_algo
C++ Boost库:字符串算法string_algo
C++ Boost库:类型推导BOOST_AUTO/BOOST_TYPEOF
C++ Boost库:分词处理库 tokenizer
C++ Boost库:windows下编译Boost库
C++ Boost库:日期时间库 date_time
C++ Boost库:智能指针scoped_ptr
C++ Boost库:数组智能指针 scoped_array
C++ Boost库:共享所有权的智能指针 shared_ptr
C++ Boost库:工厂函数 make_shared
C++ Boost库:共享有权的数组智能指针shared_array
C++ Boost库:弱引用智能指针 weak_ptr
C++ Boost库:禁止拷贝 nocopyable
C++ Boost库:计时器 timer
C++ Boost库:普通数组array
C++ Boost库:散列容器 unordered_set、unordered_multiset
C++ Boost库:散列容器 unordered_map、unordered_multimap
C++ Boost库:双向映射容器 bimap
C++ Boost库:环形缓冲区 circular_buffer
C++ Boost库:动态多维数组 multi_array
C++ Boost库:使用property_tree解析XML和JSON
C++ Boost库:简化循环 BOOST_FOREACH
C++ Boost库:随机数库 Random
C++ Boost库:引用库 ref
C++ Boost库:绑定库 bind
C++ Boost库:线程库 thread 跨平台多线程
C++ Boost库:互斥量 mutex

Highscore - Boost C++ 库 - 字符串处理

1. C/C++格式化

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

printf("%s %d %c", "hello", 111, 'C')

2. boost格式化

boost::format提供了一个和Cprintf类似的格式化字串语法定义,同时也保有了C++ostraem的各项优势,对于要做格式化输出的C++程序开发人员来说,boost::format是个相当好用的函数库。使用format需包含头文件boost/format.hpp

typedef basic_format<char> format;

示例代码:

#include  <iostream>
using namespace  std;

#include<boost/format.hpp>

int main()
{
   using boost::format;//使用format

   //使用一
   format  fmt("%1%    ,    %2%  !!!"); //先定义对象
   fmt % 123;
   fmt % "hello";
   cout << fmt << endl;

   //使用二, 可以不按顺序,可以重复指定
   format  fmt2(" %2%  ----- %1% -----   %2%  !!!"); //先定义对象
   fmt2 % 123;
   fmt2 % "hello";
   cout << fmt2 << endl;

   //使用三, 可以重复使用
   format  fmt3(" %2%  ----- %1% -----   %2%  !!!");  
   fmt3 % 123;
   fmt3 % "hello";
   cout << fmt3 << endl;

   fmt3 % 1.23456;
   fmt3 %  'C' ;
   cout << fmt3 << endl;

   //用法四,链式使用
   cout << format("****%1%****%2%!!!") % "hello"%1.2345f << endl;
   cout <<  (format("****%1%****%2%!!!") % "hello")%1.2345f << endl;

   //用法五,可以使用printf中的格式符
   cout << format(" %d   ,    %c   ,%f ,  %s") % 666 % 'A'%1.2345f%"Boost" << endl;

   //N$指定用哪个参数
   cout << format("---%2$s -----%1$s---")  %"Boost" % "Hello"<< endl;

   //用法六,直接转为string
   int  age = 20;
   const char *name = "zhangsan";

   //替代sprintf
   format  fmt6("name: %1%   age %2%");
   fmt6%name%age;

   string  strStu = fmt6.str();//直接转为字符串
   cout << strStu << endl;

   return 0;
}
  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超级D洋葱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值