开发者

Format a String in C++ with the same convenience as String.format() in Java 5 / 6? [duplicate]

开发者 https://www.devze.com 2023-03-22 14:43 出处:网络
This question already has answers here: How to construct a std::string with embedded values, i.e. "string interpol开发者_高级运维ation"?
This question already has answers here: How to construct a std::string with embedded values, i.e. "string interpol开发者_高级运维ation"? (8 answers) Closed 2 years ago.

Is there a common function available to be able to do sprintf type String formatting without having to supply a fixed size buffer, that returns a string class instance?

I know about stringstream it doesn't do what I want, I don't want to hard code the position of the tokens in the output statement like it requires.

I want to be able to define a pattern like sprintf lets you, but without the C baggage and in a more idiomatic Object Oriented C++ manner.

Maybe some function that does what sprintf does using a stringstream and produces a string object? Something along the line of the convenience of what String.format() does in Java or the equivalent String formatting syntax in Python.


The Boost Format Library:

The <boost/format.hpp> format class provides printf-like formatting, in a type-safe manner which allows output of user-defined types.


If you don't use Boost.Format or Boost.Locale you can use my simple stringstream wrapper or wrap it even further:

fakeformat

example:

REQUIRE( ff::format("{2}ff{1}").with('a').also_with(7).now()=="7ffa" );

Ideone

0

精彩评论

暂无评论...
验证码 换一张
取 消