C++ format 格式化字符串实现方式

1.

http://stackoverflow.com/questions/2342162/stdstring-formatting-like-sprintf

You can't do it directly, because you don't have write access to the underlying buffer (until C++11; see Dietrich Epp's comment). You'll have to do it first in a c-string, then copy it into a std::string:

  char buff[100];
snprintf(buff, sizeof(buff), "%s", "Hello");
std::string buffAsStdStr = buff;
But I'm not sure why you wouldn't just use a string stream? I'm assuming you have specific reasons to not just do this: std::ostringstream stringStream;
stringStream << "Hello";
std::string copyOfStr = stringStream.str();

2.

https://www.zhihu.com/question/35967887/answer/125238385

3.

boost::format

4.

http://stackoverflow.com/questions/2342162/stdstring-formatting-like-sprintf

Emphasising C++11 std::snprintf, this becomes a pretty easy and safe task. I see a lot of answers on this question that were apparently written before the time of C++11 which use fixed buffer lengths and vargs, something I would not recommend for safety, efficiency and clarity reasons.

#include <memory>
#include <iostream>
#include <string>
#include <cstdio> using namespace std; //Don't if you're in a header-file template<typename ... Args>
string string_format( const std::string& format, Args ... args )
{
size_t size = snprintf( nullptr, 0, format.c_str(), args ... ) + 1; // Extra space for '\0'
unique_ptr<char[]> buf( new char[ size ] );
snprintf( buf.get(), size, format.c_str(), args ... );
return string( buf.get(), buf.get() + size - 1 ); // We don't want the '\0' inside
}
Line by line explanation: Aim: Write to a char* by using std::snprintf and then convert that to a std::string. First, we determine the desired length of the char array. From cppreference.com: Return value [...] If the resulting string gets truncated due to buf_size limit, function returns the total number of characters (not including the terminating null-byte) which would have been written, if the limit was not imposed.
This means that the desired size is the number of characters plus one, so that the null-terminator will sit after all other characters and that it can be cut off by the string constructor again. This issue was explained by @alexk7 in the comments. Then, we allocate a new character array and assign it to a std::unique_ptr. This is generally advised, as you won't have to manually delete it again. Note that this is not a safe way to allocate a unique_ptr with user-defined types as you can not deallocate the memory if the constructor throws an exception! After that, we can of course just use snprintf for its intended use and write the formatted string to the char[] and afterwards create and return a new std::string from that. You can see an example in action here. Additional information for Visual Studio users: As explained in this answer, Microsoft renamed std::snprintf to _snprintf (yes, without std::). MS further set it as deprecated and advises to use _snprintf_s instead, however _snprintf_s won't accept the buffer to be zero or smaller than the formatted output and will not calculate the outputs length if that occurs. So in order to get rid of the deprecation warnings during compilation, you can insert the following line at the top of the file which contains the use of _snprintf: #pragma warning(disable : 4996)

5.

https://github.com/fmtlib/fmt#compile-time-and-code-bloat

fmt is an open-source formatting library for C++. It can be used as a safe alternative to printf or as a fast alternative to IOStreams.

6.

https://github.com/c42f/tinyformat

tinyformat.h is a type safe printf replacement library in a single C++ header file. If you've ever wanted printf("%s", s) to just work regardless of the type of s, tinyformat might be for you. Design goals include:

Type safety and extensibility for user defined types.

C99 printf() compatibility, to the extent possible using std::ostream

Simplicity and minimalism. A single header file to include and distribute with your projects.

Augment rather than replace the standard stream formatting mechanism

C++98 support, with optional C++11 niceties

##C++ format 格式化字符串的更多相关文章

  1. .NET ToString() format格式化字符串(常用)

    前言 我们平常会用到货币数据类型,尤其当我们计算金钱或者算数的时候经常会遇到保留几位小数,而且碰到日期格式问题的时候,经常不知道选择什么样的格式比较合适,下面我找了一部分常用的.NET ToStrin ...

  2. %----format 格式化字符串---- 生成器---- 迭代器

    %方式格式化字符串 顺序传参数 o转换8进制x转换十六进制 tp1 = "i am %s" % "alex"tp2 = "i am %s age %d ...

  3. .NET C# Tostring() format 格式化字符串大全

    C 货币 2.5.ToString("C") ¥2.50 D 十进制数 25.ToString("D5") 00025 E 科学型 25000.ToString ...

  4. Python用format格式化字符串

    format是是python2.6新增的一个格式化字符串的方法,相对于老版的%格式方法,它有很多优点. 1.不需要理会数据类型的问题,在%方法中%s只能替代字符串类型 2.单个参数可以多次输出,参数顺 ...

  5. java中实现与.net的format格式化字符串输出

    Java中的格式化字符串 System.out.println(MessageFormat.format("name={0}", "张三")); .net中的格 ...

  6. string.format格式化字符串中转义大括号“{}”

    今天,用Java读取配置文件占位符,使用String.Format(string format,object arg0)方法.以前只知“{0}”为索引占位符(即格式项),与参数列表中的第一个对象相对应 ...

  7. python format格式化字符串

    自python2.6开始,新增了一种格式化字符串的函数str.format() 语法 它通过{}和:来代替%. “映射”示例 通过位置 In [1]: '{0},{1}'.format('kzc',1 ...

  8. format格式化字符串

    假如想要表达这样一条语句:李明今年十二岁 输出这样一条语句 name = 'LiMing' age = 12 print( name + 'is' + age + 'years old') #输出 L ...

  9. String.format() 格式化字符串

    1.几种常见的转换符 转换符 说明 实例 %d 整数类型(十进制) 99 %f 浮点类型 99.99 %s 字符串类型 "mingrisoft" %c 字符类型 'm' %b 布尔 ...

随机推荐

  1. Appium+python自动化(七)- 初识琵琶女Appium(千呼万唤始出来,犹抱琵琶半遮面)- 上(超详解)

    简介 “千呼万唤始出来,犹抱琵琶半遮面”,经过前边的各项准备工作,终于才把appium这位琵琶女请出来.那么下边就由宏哥给各位看官.小伙伴们和童鞋们来引荐这位美女(帅哥).这一篇主要是对前边的内容做一 ...

  2. 【linux】Too many open files 解决问题第一步【记录】

    记录一下解决linux上出现:Too many open files  的第一步骤. 做个记录,免得每次都查来查去的. 1.查看 ulimit -a 2.修改 vi /etc/security/lim ...

  3. 14、VUE服务器渲染

    1.HTML的渲染方式 1.1. 浏览器本地渲染 这种方式不会被搜索引擎获取内容,所以不利于网站的推广. 因为浏览器本地渲染是页面js通过发送ajax请求获取后台的json数据,然后生成页面内容. 爬 ...

  4. python 动态创建变量 获取变量名

    参考链接:https://www.cnblogs.com/technologylife/p/9211324.html 参考链接(未)(使用inspect 获取变量名):https://blog.csd ...

  5. 极速体验docker容器健康

    本文目是体验docker容器的健康检查功能,以体验为主不涉及开发,与开发相关的内容会在后面的文章细说. 关于容器健康检查 考虑这样的情况:docker环境中,springboot应用的容器还在,但已无 ...

  6. echarts 更改tooltip提示框CSS样式

    最近 做项目,用过echarts,发现tooltip提示z-index级别很高,想更改下,看了下文档:https://www.echartsjs.com/zh/option.html#tooltip. ...

  7. CRM产品主数据在行业解决方案industry solution中的应用

    AG3, choose this role: Create a new Acquisition Contracts: Here our product advances search will be ...

  8. Fundebug前端JavaScript插件更新至1.8.0,兼容低版本的Android浏览器

    摘要: 兼容低版本Android浏览器,请大家及时更新. Fundebug前端BUG监控服务 Fundebug是专业的程序BUG监控平台,我们JavaScript插件可以提供全方位的BUG监控,可以帮 ...

  9. C++ OpenSSL 之五:生成P12文件

    1.等同于使用: openssl pkcs12 -export -inkey "key_path" -in "pem_path" -out "save ...

  10. 微信小程序+php 授权登陆,完整代码

    先上图        实现流程: 1.授权登陆按钮和正文信息放到了同一个页面,未授权的时候显示登陆按钮,已授权的时候隐藏登陆按钮,显示正文信息,当然也可以授权和正文分开成两个页面,在授权页面的onlo ...