If you want to use printf
like formatting you should probably use snprintf
(or build an allocating variant of that on top of that). Note that sprintf
requires you to be able to guarantee that the result will not overrun the buffer you have to keep defined behaviour. With snprintf
on the other hand can guarantee that it will not overrun the buffer since you specifiy the maximal number of characters that will be written to the string (it will instead truncate the output).
You could even build something that can directly be fed to an ostream
on top of snprintf
by automatically allocate the buffer and place in an object that on destruction free that memory. This in addition with a method to feed the object to an ostream
would finish it off.
struct FMT {
char buf[2048];
FMT(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
}
};
inline std::ostream& operator<< (std::ostream& os, FMT const& str) { os << (const char*)str.buf; return os; }
then you use this as:
cout << FMT("The answer is %d", 42) << endl;
If you're using the GNU libraries you could of course use printf
directly since cout
and stdout
are the same object then. Otherwise you should probably avoid mixing stdio
and iostreams
as there is no guarantee that these are synchronized with each other.
setprecision
:std::cout << std::fixed << std::setprecision(2) << dNum;
– Stipel