I have to format std::string
with sprintf
and send it into file stream. How can I do this?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- how to split a list into a given number of sub-lis
- thread_local variables initialization
相关文章
- JSP String formatting Truncate
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
I wrote my own using vsnprintf so it returns string instead of having to create my own buffer.
So you can use it like
You could try this:
Unfortunately, most of the answers here use varargs which are inherently unsafe unless you use something like GCC's
format
attribute which only works with literal format strings. You can see why these functions are unsafe on the following example:where
string_format
is an implementation from the Erik Aronesty's answer. This code compiles, but it will most likely crash when you try to run it:It is possible to implement a safe
printf
and extend it to formatstd::string
using (variadic) templates. This has been done in the {fmt} library, which provides a safe alternative tosprintf
returningstd::string
:{fmt} keeps track of the argument types and if the type doesn't match format specification there is no segmentation fault, just an exception or a compile-time error if
constexpr
format string checks are used.Disclaimer: I'm the author of {fmt}.
I usually use this:
Disadvantage: not all systems support vasprint
Below slightly modified version of @iFreilicht answer, updated to C++14 (usage of
make_unique
function instead of raw declaration) and added support forstd::string
arguments (based on Kenny Kerr article)Output:
Feel free to merge this answer with the original one if desired.