How do I send a format string to iostream? [duplicate]
-
03-07-2021 - |
質問
Possible Duplicate:
std::string formatting like sprintf
Can I use the c++ iostream classes with a format string like printf?
Basically, I want to be able to do something like :-
snprintf (inchars, len, "%4f %6.2f %3d \n", float1, float2, int1);
easily using stringstreams. Is there an easy way to do this?
解決
Yes, there's the Boost Format Library (which is stringstreams internally).
#include <boost/format.hpp>
#include <iostream>
int main() {
std::cout << boost::format("%s %s!\n") % "Hello" % "World";
return 0;
}
他のヒント
You can write a wrapper function that returns something that you can deliver into an ostringstream.
This function combines some of the solutions presented in the link moooeeeep pointed out in comments:
std::string string_format(const char *fmt, ...) {
std::vector<char> str(100);
va_list ap;
while (1) {
va_start(ap, fmt);
int n = vsnprintf(&str[0], str.size(), fmt, ap);
va_end(ap);
if (n > -1 && n < str.size()) {
str.resize(n);
return &str[0];
}
str.resize(str.size() * 2);
}
}
This kind of formatting takes quite a bit more effort using standard C++ streams. In particular, you have to use stream manipulators which can specify the number of digits to show after the decimal place.
所属していません StackOverflow