##C++ format 格式化字符串
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 格式化字符串的更多相关文章
- .NET ToString() format格式化字符串(常用)
前言 我们平常会用到货币数据类型,尤其当我们计算金钱或者算数的时候经常会遇到保留几位小数,而且碰到日期格式问题的时候,经常不知道选择什么样的格式比较合适,下面我找了一部分常用的.NET ToStrin ...
- %----format 格式化字符串---- 生成器---- 迭代器
%方式格式化字符串 顺序传参数 o转换8进制x转换十六进制 tp1 = "i am %s" % "alex"tp2 = "i am %s age %d ...
- .NET C# Tostring() format 格式化字符串大全
C 货币 2.5.ToString("C") ¥2.50 D 十进制数 25.ToString("D5") 00025 E 科学型 25000.ToString ...
- Python用format格式化字符串
format是是python2.6新增的一个格式化字符串的方法,相对于老版的%格式方法,它有很多优点. 1.不需要理会数据类型的问题,在%方法中%s只能替代字符串类型 2.单个参数可以多次输出,参数顺 ...
- java中实现与.net的format格式化字符串输出
Java中的格式化字符串 System.out.println(MessageFormat.format("name={0}", "张三")); .net中的格 ...
- string.format格式化字符串中转义大括号“{}”
今天,用Java读取配置文件占位符,使用String.Format(string format,object arg0)方法.以前只知“{0}”为索引占位符(即格式项),与参数列表中的第一个对象相对应 ...
- python format格式化字符串
自python2.6开始,新增了一种格式化字符串的函数str.format() 语法 它通过{}和:来代替%. “映射”示例 通过位置 In [1]: '{0},{1}'.format('kzc',1 ...
- format格式化字符串
假如想要表达这样一条语句:李明今年十二岁 输出这样一条语句 name = 'LiMing' age = 12 print( name + 'is' + age + 'years old') #输出 L ...
- String.format() 格式化字符串
1.几种常见的转换符 转换符 说明 实例 %d 整数类型(十进制) 99 %f 浮点类型 99.99 %s 字符串类型 "mingrisoft" %c 字符类型 'm' %b 布尔 ...
随机推荐
- 循环节 + 矩阵快速幂 - HDU 4291 A Short problem
A Short problem Problem's Link Mean: 给定一个n,求:g(g(g(n))) % 1000000007 其中:g(n) = 3g(n - 1) + g(n - 2), ...
- nginx 的一些优化(突破十万并发)
一般来说 nginx 配置文件中对优化比较有作用的为以下几项: worker_processes 8; nginx 进程数,建议按照 cpu 数目来指定,一般为它的倍数. worker_cpu_aff ...
- Lock+Condition实现机制
前言:大部分多线程同步场景,在功能和性能层面,synchronized可以满足,少部分场景Lock可以满足,dubbo的源码也符合这个比例,需要使用到Condition的场景极少,整个dubbo源码中 ...
- Markdown温故知新(3):六个实用扩展语法
目录 1.表格(Table) 2.待办事项或清单(To Do List) 3.自动目录 TOC 4.流程图 5.时序图 6.甘特图 7.总结 1.表格(Table) 没用过 Markdown 表格的人 ...
- python动态视频下载器
这里向大家分享一下python爬虫的一些应用,主要是用爬虫配合简单的GUI界面实现视频,音乐和小说的下载器.今天就先介绍如何实现一个动态视频下载器. 爬取电影天堂视频 首先介绍的是python爬取电影 ...
- response.Close、response.End、response.Flush区别(下载文件)
今天在做文件下载功能用到的是response的方法,首先我们要了解这些方法的作用. 1.response.write():将信息写入http响应输出流. 2.response.Flush:向客户端发送 ...
- tcbRouter
tcb-router 基于koa风格的小程序·云开发云函数轻量级类路由库,主要用于优化服务端函数处理逻辑 安装 在云函数当前目录下安装:npm install --save tcb-router 使 ...
- Java操作ElasticSearch之创建客户端连接
Java操作ElasticSearch之创建客户端连接 3 发布时间:『 2017-09-11 17:02』 博客类别:elasticsearch 阅读(3157) Java操作ElasticSe ...
- Spark GraphX图计算简单案例【代码实现,源码分析】
一.简介 参考:https://www.cnblogs.com/yszd/p/10186556.html 二.代码实现 package big.data.analyse.graphx import o ...
- windows,linux里的hosts文件
在解析主机名的IP地址时,会先访问本机的上hosts文件,这样先配置好就可以不通过DNS服务器就获得IP地址. linux vi /etc/hosts IP 空格 主机名 windows C:\Wi ...