I have to format std::string with sprintf and send it into file stream. How can I do this?
C++20 will include std::format which resembles sprintf
in terms of API but is fully type-safe, works with user-defined types, and uses Python-like format string syntax. Here's how you will be able to format std::string
and write it to a stream:
std::string s = "foo";
std::cout << std::format("Look, a string: {}", s);
or
std::string s = "foo";
puts(std::format("Look, a string: {}", s).c_str());
Alternatively, you could use the {fmt} library to format a string and write it to stdout
or a file stream in one go:
fmt::print(f, "Look, a string: {}", s); // where f is a file stream
As for sprintf
or most of the other answers here, unfortunately they use varargs and 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:
std::string format_str = "%s";
string_format(format_str, format_str[0]);
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:
$ g++ -Wall -Wextra -pedantic test.cc
$ ./a.out
Segmentation fault: 11
Disclaimer: I'm the author of {fmt} and C++20 std::format
.